This repository has been archived by the owner on Sep 11, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 19
/
laf-intel.diff
1255 lines (1249 loc) · 45.1 KB
/
laf-intel.diff
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
diff -urN ./laf-intel.usage ./laf-intel.usage
--- ./llvm_mode/README.laf-intel 1970-01-01 01:00:00.000000000 +0100
+++ ./llvm_mode/README.laf-intel 2019-01-09 21:41:01.928365797 +0100
@@ -0,0 +1,13 @@
+Usage
+By default the passes will not run when you compile programs using
+afl-clang-fast. Hence, you can use AFL as usual. To enable the passes you must
+set environment variables before you compile the target project.
+
+
+export LAF_SPLIT_SWITCHES=1 Enables the split-switches pass.
+
+export LAF_TRANSFORM_COMPARES=1 Enables the transform-compares pass (strcmp, memcmp, strncmp, strcasecmp, strncasecmp).
+
+export LAF_SPLIT_COMPARES=1 Enables the split-compares pass. By default it will split all compares with
+a bit width <= 64 bits. You can change this behaviour by setting export LAF_SPLIT_COMPARES_BITW=<bit_width>.
+
diff -urN ./llvm_mode/afl-clang-fast.c ./llvm_mode/afl-clang-fast.c
--- ./llvm_mode/afl-clang-fast.c 2017-01-25 03:51:26.000000000 +0100
+++ ./llvm_mode/afl-clang-fast.c 2018-12-27 15:23:41.710341000 +0100
@@ -119,6 +119,29 @@
http://clang.llvm.org/docs/SanitizerCoverage.html#tracing-pcs-with-guards */
+ // laf
+ if (getenv("LAF_SPLIT_SWITCHES")) {
+ cc_params[cc_par_cnt++] = "-Xclang";
+ cc_params[cc_par_cnt++] = "-load";
+ cc_params[cc_par_cnt++] = "-Xclang";
+ cc_params[cc_par_cnt++] = alloc_printf("%s/split-switches-pass.so", obj_path);
+ }
+
+ if (getenv("LAF_TRANSFORM_COMPARES")) {
+ cc_params[cc_par_cnt++] = "-Xclang";
+ cc_params[cc_par_cnt++] = "-load";
+ cc_params[cc_par_cnt++] = "-Xclang";
+ cc_params[cc_par_cnt++] = alloc_printf("%s/compare-transform-pass.so", obj_path);
+ }
+
+ if (getenv("LAF_SPLIT_COMPARES")) {
+ cc_params[cc_par_cnt++] = "-Xclang";
+ cc_params[cc_par_cnt++] = "-load";
+ cc_params[cc_par_cnt++] = "-Xclang";
+ cc_params[cc_par_cnt++] = alloc_printf("%s/split-compares-pass.so", obj_path);
+ }
+ // /laf
+
#ifdef USE_TRACE_PC
cc_params[cc_par_cnt++] = "-fsanitize-coverage=trace-pc-guard";
cc_params[cc_par_cnt++] = "-mllvm";
diff -urN ./llvm_mode/compare-transform-pass.so.cc ./llvm_mode/compare-transform-pass.so.cc
--- ./llvm_mode/compare-transform-pass.so.cc 1970-01-01 01:00:00.000000000 +0100
+++ ./llvm_mode/compare-transform-pass.so.cc 2019-01-09 22:36:59.184886414 +0100
@@ -0,0 +1,307 @@
+/*
+ * Copyright 2016 laf-intel
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <unistd.h>
+
+#include "llvm/ADT/Statistic.h"
+#include "llvm/IR/IRBuilder.h"
+#include "llvm/IR/LegacyPassManager.h"
+#include "llvm/IR/Module.h"
+#include "llvm/Support/Debug.h"
+#include "llvm/Support/raw_ostream.h"
+#include "llvm/Transforms/IPO/PassManagerBuilder.h"
+#include "llvm/Transforms/Utils/BasicBlockUtils.h"
+#include "llvm/IR/Verifier.h"
+#include "llvm/Pass.h"
+#include "llvm/Analysis/ValueTracking.h"
+
+#include <set>
+
+using namespace llvm;
+
+namespace {
+
+ class CompareTransform : public ModulePass {
+
+ public:
+ static char ID;
+ CompareTransform() : ModulePass(ID) {
+ }
+
+ bool runOnModule(Module &M) override;
+
+#if __clang_major__ < 4
+ const char * getPassName() const override {
+#else
+ StringRef getPassName() const override {
+#endif
+ return "transforms compare functions";
+ }
+ private:
+ bool transformCmps(Module &M, const bool processStrcmp, const bool processMemcmp
+ ,const bool processStrncmp, const bool processStrcasecmp, const bool processStrncasecmp);
+ };
+}
+
+
+char CompareTransform::ID = 0;
+
+bool CompareTransform::transformCmps(Module &M, const bool processStrcmp, const bool processMemcmp
+ , const bool processStrncmp, const bool processStrcasecmp, const bool processStrncasecmp) {
+
+ std::vector<CallInst*> calls;
+ LLVMContext &C = M.getContext();
+ IntegerType *Int8Ty = IntegerType::getInt8Ty(C);
+ IntegerType *Int32Ty = IntegerType::getInt32Ty(C);
+ IntegerType *Int64Ty = IntegerType::getInt64Ty(C);
+ Constant* c = M.getOrInsertFunction("tolower",
+ Int32Ty,
+ Int32Ty
+#if __clang_major__ < 7
+ , nullptr
+#endif
+ );
+ Function* tolowerFn = cast<Function>(c);
+
+ /* iterate over all functions, bbs and instruction and add suitable calls to strcmp/memcmp/strncmp/strcasecmp/strncasecmp */
+ for (auto &F : M) {
+ for (auto &BB : F) {
+ for(auto &IN: BB) {
+ CallInst* callInst = nullptr;
+
+ if ((callInst = dyn_cast<CallInst>(&IN))) {
+
+ bool isStrcmp = processStrcmp;
+ bool isMemcmp = processMemcmp;
+ bool isStrncmp = processStrncmp;
+ bool isStrcasecmp = processStrcasecmp;
+ bool isStrncasecmp = processStrncasecmp;
+
+ Function *Callee = callInst->getCalledFunction();
+ if (!Callee)
+ continue;
+ if (callInst->getCallingConv() != llvm::CallingConv::C)
+ continue;
+ StringRef FuncName = Callee->getName();
+ isStrcmp &= !FuncName.compare(StringRef("strcmp"));
+ isMemcmp &= !FuncName.compare(StringRef("memcmp"));
+ isStrncmp &= !FuncName.compare(StringRef("strncmp"));
+ isStrcasecmp &= !FuncName.compare(StringRef("strcasecmp"));
+ isStrncasecmp &= !FuncName.compare(StringRef("strncasecmp"));
+
+ if (!isStrcmp && !isMemcmp && !isStrncmp && !isStrcasecmp && !isStrncasecmp)
+ continue;
+
+ /* Verify the strcmp/memcmp/strncmp/strcasecmp/strncasecmp function prototype */
+ FunctionType *FT = Callee->getFunctionType();
+
+
+ isStrcmp &= FT->getNumParams() == 2 &&
+ FT->getReturnType()->isIntegerTy(32) &&
+ FT->getParamType(0) == FT->getParamType(1) &&
+ FT->getParamType(0) == IntegerType::getInt8PtrTy(M.getContext());
+ isStrcasecmp &= FT->getNumParams() == 2 &&
+ FT->getReturnType()->isIntegerTy(32) &&
+ FT->getParamType(0) == FT->getParamType(1) &&
+ FT->getParamType(0) == IntegerType::getInt8PtrTy(M.getContext());
+ isMemcmp &= FT->getNumParams() == 3 &&
+ FT->getReturnType()->isIntegerTy(32) &&
+ FT->getParamType(0)->isPointerTy() &&
+ FT->getParamType(1)->isPointerTy() &&
+ FT->getParamType(2)->isIntegerTy();
+ isStrncmp &= FT->getNumParams() == 3 &&
+ FT->getReturnType()->isIntegerTy(32) &&
+ FT->getParamType(0) == FT->getParamType(1) &&
+ FT->getParamType(0) == IntegerType::getInt8PtrTy(M.getContext()) &&
+ FT->getParamType(2)->isIntegerTy();
+ isStrncasecmp &= FT->getNumParams() == 3 &&
+ FT->getReturnType()->isIntegerTy(32) &&
+ FT->getParamType(0) == FT->getParamType(1) &&
+ FT->getParamType(0) == IntegerType::getInt8PtrTy(M.getContext()) &&
+ FT->getParamType(2)->isIntegerTy();
+
+ if (!isStrcmp && !isMemcmp && !isStrncmp && !isStrcasecmp && !isStrncasecmp)
+ continue;
+
+ /* is a str{n,}{case,}cmp/memcmp, check is we have
+ * str{case,}cmp(x, "const") or str{case,}cmp("const", x)
+ * strn{case,}cmp(x, "const", ..) or strn{case,}cmp("const", x, ..)
+ * memcmp(x, "const", ..) or memcmp("const", x, ..) */
+ Value *Str1P = callInst->getArgOperand(0), *Str2P = callInst->getArgOperand(1);
+ StringRef Str1, Str2;
+ bool HasStr1 = getConstantStringInfo(Str1P, Str1);
+ bool HasStr2 = getConstantStringInfo(Str2P, Str2);
+
+ /* handle cases of one string is const, one string is variable */
+ if (!(HasStr1 ^ HasStr2))
+ continue;
+
+ if (isMemcmp || isStrncmp || isStrncasecmp) {
+ /* check if third operand is a constant integer
+ * strlen("constStr") and sizeof() are treated as constant */
+ Value *op2 = callInst->getArgOperand(2);
+ ConstantInt* ilen = dyn_cast<ConstantInt>(op2);
+ if (!ilen)
+ continue;
+ /* final precaution: if size of compare is larger than constant string skip it*/
+ uint64_t literalLength = HasStr1 ? GetStringLength(Str1P) : GetStringLength(Str2P);
+ if (literalLength < ilen->getZExtValue())
+ continue;
+ }
+
+ calls.push_back(callInst);
+ }
+ }
+ }
+ }
+
+ if (!calls.size())
+ return false;
+ errs() << "Replacing " << calls.size() << " calls to strcmp/memcmp/strncmp/strcasecmp/strncasecmp\n";
+
+ for (auto &callInst: calls) {
+
+ Value *Str1P = callInst->getArgOperand(0), *Str2P = callInst->getArgOperand(1);
+ StringRef Str1, Str2, ConstStr;
+ Value *VarStr;
+ bool HasStr1 = getConstantStringInfo(Str1P, Str1);
+ getConstantStringInfo(Str2P, Str2);
+ uint64_t constLen, sizedLen;
+ bool isMemcmp = !callInst->getCalledFunction()->getName().compare(StringRef("memcmp"));
+ bool isSizedcmp = isMemcmp
+ || !callInst->getCalledFunction()->getName().compare(StringRef("strncmp"))
+ || !callInst->getCalledFunction()->getName().compare(StringRef("strncasecmp"));
+ bool isCaseInsensitive = !callInst->getCalledFunction()->getName().compare(StringRef("strcasecmp"))
+ || !callInst->getCalledFunction()->getName().compare(StringRef("strncasecmp"));
+
+ if (isSizedcmp) {
+ Value *op2 = callInst->getArgOperand(2);
+ ConstantInt* ilen = dyn_cast<ConstantInt>(op2);
+ sizedLen = ilen->getZExtValue();
+ }
+
+ if (HasStr1) {
+ ConstStr = Str1;
+ VarStr = Str2P;
+ constLen = isMemcmp ? sizedLen : GetStringLength(Str1P);
+ }
+ else {
+ ConstStr = Str2;
+ VarStr = Str1P;
+ constLen = isMemcmp ? sizedLen : GetStringLength(Str2P);
+ }
+ if (isSizedcmp && constLen > sizedLen) {
+ constLen = sizedLen;
+ }
+
+ errs() << callInst->getCalledFunction()->getName() << ": len " << constLen << ": " << ConstStr << "\n";
+
+ /* split before the call instruction */
+ BasicBlock *bb = callInst->getParent();
+ BasicBlock *end_bb = bb->splitBasicBlock(BasicBlock::iterator(callInst));
+ BasicBlock *next_bb = BasicBlock::Create(C, "cmp_added", end_bb->getParent(), end_bb);
+ BranchInst::Create(end_bb, next_bb);
+ PHINode *PN = PHINode::Create(Int32Ty, constLen + 1, "cmp_phi");
+
+ TerminatorInst *term = bb->getTerminator();
+ BranchInst::Create(next_bb, bb);
+ term->eraseFromParent();
+
+ for (uint64_t i = 0; i < constLen; i++) {
+
+ BasicBlock *cur_bb = next_bb;
+
+ char c = isCaseInsensitive ? tolower(ConstStr[i]) : ConstStr[i];
+
+
+ BasicBlock::iterator IP = next_bb->getFirstInsertionPt();
+ IRBuilder<> IRB(&*IP);
+
+ Value* v = ConstantInt::get(Int64Ty, i);
+ Value *ele = IRB.CreateInBoundsGEP(VarStr, v, "empty");
+ Value *load = IRB.CreateLoad(ele);
+ if (isCaseInsensitive) {
+ // load >= 'A' && load <= 'Z' ? load | 0x020 : load
+ std::vector<Value *> args;
+ args.push_back(load);
+ load = IRB.CreateCall(tolowerFn, args, "tmp");
+ }
+ Value *isub;
+ if (HasStr1)
+ isub = IRB.CreateSub(ConstantInt::get(Int8Ty, c), load);
+ else
+ isub = IRB.CreateSub(load, ConstantInt::get(Int8Ty, c));
+
+ Value *sext = IRB.CreateSExt(isub, Int32Ty);
+ PN->addIncoming(sext, cur_bb);
+
+
+ if (i < constLen - 1) {
+ next_bb = BasicBlock::Create(C, "cmp_added", end_bb->getParent(), end_bb);
+ BranchInst::Create(end_bb, next_bb);
+
+ TerminatorInst *term = cur_bb->getTerminator();
+ Value *icmp = IRB.CreateICmpEQ(isub, ConstantInt::get(Int8Ty, 0));
+ IRB.CreateCondBr(icmp, next_bb, end_bb);
+ term->eraseFromParent();
+ } else {
+ //IRB.CreateBr(end_bb);
+ }
+
+ //add offset to varstr
+ //create load
+ //create signed isub
+ //create icmp
+ //create jcc
+ //create next_bb
+ }
+
+ /* since the call is the first instruction of the bb it is safe to
+ * replace it with a phi instruction */
+ BasicBlock::iterator ii(callInst);
+ ReplaceInstWithInst(callInst->getParent()->getInstList(), ii, PN);
+ }
+
+
+ return true;
+}
+
+bool CompareTransform::runOnModule(Module &M) {
+
+ llvm::errs() << "Running compare-transform-pass by laf.intel@gmail.com, extended by heiko@hexco.de\n";
+ transformCmps(M, true, true, true, true, true);
+ verifyModule(M);
+
+ return true;
+}
+
+static void registerCompTransPass(const PassManagerBuilder &,
+ legacy::PassManagerBase &PM) {
+
+ auto p = new CompareTransform();
+ PM.add(p);
+
+}
+
+static RegisterStandardPasses RegisterCompTransPass(
+ PassManagerBuilder::EP_OptimizerLast, registerCompTransPass);
+
+static RegisterStandardPasses RegisterCompTransPass0(
+ PassManagerBuilder::EP_EnabledOnOptLevel0, registerCompTransPass);
+
diff -urN ./llvm_mode/Makefile ./llvm_mode/Makefile
--- ./llvm_mode/Makefile 2016-06-24 04:38:49.000000000 +0200
+++ ./llvm_mode/Makefile 2018-12-27 15:19:18.086346000 +0100
@@ -55,9 +55,9 @@
endif
ifndef AFL_TRACE_PC
- PROGS = ../afl-clang-fast ../afl-llvm-pass.so ../afl-llvm-rt.o ../afl-llvm-rt-32.o ../afl-llvm-rt-64.o
+ PROGS = ../afl-clang-fast ../afl-llvm-pass.so ../afl-llvm-rt.o ../afl-llvm-rt-32.o ../afl-llvm-rt-64.o ../compare-transform-pass.so ../split-compares-pass.so ../split-switches-pass.so
else
- PROGS = ../afl-clang-fast ../afl-llvm-rt.o ../afl-llvm-rt-32.o ../afl-llvm-rt-64.o
+ PROGS = ../afl-clang-fast ../afl-llvm-rt.o ../afl-llvm-rt-32.o ../afl-llvm-rt-64.o ../compare-transform-pass.so ../split-compares-pass.so ../split-switches-pass.so
endif
all: test_deps $(PROGS) test_build all_done
@@ -82,6 +82,16 @@
../afl-llvm-pass.so: afl-llvm-pass.so.cc | test_deps
$(CXX) $(CLANG_CFL) -shared $< -o $@ $(CLANG_LFL)
+# laf
+../split-switches-pass.so: split-switches-pass.so.cc | test_deps
+ $(CXX) $(CLANG_CFL) -shared $< -o $@ $(CLANG_LFL)
+../compare-transform-pass.so: compare-transform-pass.so.cc | test_deps
+ $(CXX) $(CLANG_CFL) -shared $< -o $@ $(CLANG_LFL)
+../split-compares-pass.so: split-compares-pass.so.cc | test_deps
+ $(CXX) $(CLANG_CFL) -shared $< -o $@ $(CLANG_LFL)
+
+# /laf
+
../afl-llvm-rt.o: afl-llvm-rt.o.c | test_deps
$(CC) $(CFLAGS) -fPIC -c $< -o $@
diff -urN ./llvm_mode/split-compares-pass.so.cc ./llvm_mode/split-compares-pass.so.cc
--- ./llvm_mode/split-compares-pass.so.cc 1970-01-01 01:00:00.000000000 +0100
+++ ./llvm_mode/split-compares-pass.so.cc 2019-01-08 17:17:05.564960249 +0100
@@ -0,0 +1,527 @@
+/*
+ * Copyright 2016 laf-intel
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include "llvm/Pass.h"
+#include "llvm/Support/raw_ostream.h"
+#include "llvm/IR/LegacyPassManager.h"
+#include "llvm/Transforms/IPO/PassManagerBuilder.h"
+#include "llvm/Transforms/Utils/BasicBlockUtils.h"
+#include "llvm/IR/Verifier.h"
+#include "llvm/IR/Module.h"
+
+#include "llvm/IR/IRBuilder.h"
+
+using namespace llvm;
+
+namespace {
+ class SplitComparesTransform : public ModulePass {
+ public:
+ static char ID;
+ SplitComparesTransform() : ModulePass(ID) {}
+
+ bool runOnModule(Module &M) override;
+#if __clang_major__ >= 4
+ StringRef getPassName() const override {
+#else
+ const char * getPassName() const override {
+#endif
+ return "simplifies and splits ICMP instructions";
+ }
+ private:
+ bool splitCompares(Module &M, unsigned bitw);
+ bool simplifyCompares(Module &M);
+ bool simplifySignedness(Module &M);
+
+ };
+}
+
+char SplitComparesTransform::ID = 0;
+
+/* This function splits ICMP instructions with xGE or xLE predicates into two
+ * ICMP instructions with predicate xGT or xLT and EQ */
+bool SplitComparesTransform::simplifyCompares(Module &M) {
+ LLVMContext &C = M.getContext();
+ std::vector<Instruction*> icomps;
+ IntegerType *Int1Ty = IntegerType::getInt1Ty(C);
+
+ /* iterate over all functions, bbs and instruction and add
+ * all integer comparisons with >= and <= predicates to the icomps vector */
+ for (auto &F : M) {
+ for (auto &BB : F) {
+ for (auto &IN: BB) {
+ CmpInst* selectcmpInst = nullptr;
+
+ if ((selectcmpInst = dyn_cast<CmpInst>(&IN))) {
+
+ if (selectcmpInst->getPredicate() != CmpInst::ICMP_UGE &&
+ selectcmpInst->getPredicate() != CmpInst::ICMP_SGE &&
+ selectcmpInst->getPredicate() != CmpInst::ICMP_ULE &&
+ selectcmpInst->getPredicate() != CmpInst::ICMP_SLE ) {
+ continue;
+ }
+
+ auto op0 = selectcmpInst->getOperand(0);
+ auto op1 = selectcmpInst->getOperand(1);
+
+ IntegerType* intTyOp0 = dyn_cast<IntegerType>(op0->getType());
+ IntegerType* intTyOp1 = dyn_cast<IntegerType>(op1->getType());
+
+ /* this is probably not needed but we do it anyway */
+ if (!intTyOp0 || !intTyOp1) {
+ continue;
+ }
+
+ icomps.push_back(selectcmpInst);
+ }
+ }
+ }
+ }
+
+ if (!icomps.size()) {
+ return false;
+ }
+
+
+ for (auto &IcmpInst: icomps) {
+ BasicBlock* bb = IcmpInst->getParent();
+
+ auto op0 = IcmpInst->getOperand(0);
+ auto op1 = IcmpInst->getOperand(1);
+
+ /* find out what the new predicate is going to be */
+ auto pred = dyn_cast<CmpInst>(IcmpInst)->getPredicate();
+ CmpInst::Predicate new_pred;
+ switch(pred) {
+ case CmpInst::ICMP_UGE:
+ new_pred = CmpInst::ICMP_UGT;
+ break;
+ case CmpInst::ICMP_SGE:
+ new_pred = CmpInst::ICMP_SGT;
+ break;
+ case CmpInst::ICMP_ULE:
+ new_pred = CmpInst::ICMP_ULT;
+ break;
+ case CmpInst::ICMP_SLE:
+ new_pred = CmpInst::ICMP_SLT;
+ break;
+ default: // keep the compiler happy
+ continue;
+ }
+
+ /* split before the icmp instruction */
+ BasicBlock* end_bb = bb->splitBasicBlock(BasicBlock::iterator(IcmpInst));
+
+ /* the old bb now contains a unconditional jump to the new one (end_bb)
+ * we need to delete it later */
+
+ /* create the ICMP instruction with new_pred and add it to the old basic
+ * block bb it is now at the position where the old IcmpInst was */
+ Instruction* icmp_np;
+ icmp_np = CmpInst::Create(Instruction::ICmp, new_pred, op0, op1);
+ bb->getInstList().insert(bb->getTerminator()->getIterator(), icmp_np);
+
+ /* create a new basic block which holds the new EQ icmp */
+ Instruction *icmp_eq;
+ /* insert middle_bb before end_bb */
+ BasicBlock* middle_bb = BasicBlock::Create(C, "injected",
+ end_bb->getParent(), end_bb);
+ icmp_eq = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ, op0, op1);
+ middle_bb->getInstList().push_back(icmp_eq);
+ /* add an unconditional branch to the end of middle_bb with destination
+ * end_bb */
+ BranchInst::Create(end_bb, middle_bb);
+
+ /* replace the uncond branch with a conditional one, which depends on the
+ * new_pred icmp. True goes to end, false to the middle (injected) bb */
+ auto term = bb->getTerminator();
+ BranchInst::Create(end_bb, middle_bb, icmp_np, bb);
+ term->eraseFromParent();
+
+
+ /* replace the old IcmpInst (which is the first inst in end_bb) with a PHI
+ * inst to wire up the loose ends */
+ PHINode *PN = PHINode::Create(Int1Ty, 2, "");
+ /* the first result depends on the outcome of icmp_eq */
+ PN->addIncoming(icmp_eq, middle_bb);
+ /* if the source was the original bb we know that the icmp_np yielded true
+ * hence we can hardcode this value */
+ PN->addIncoming(ConstantInt::get(Int1Ty, 1), bb);
+ /* replace the old IcmpInst with our new and shiny PHI inst */
+ BasicBlock::iterator ii(IcmpInst);
+ ReplaceInstWithInst(IcmpInst->getParent()->getInstList(), ii, PN);
+ }
+
+ return true;
+}
+
+/* this function transforms signed compares to equivalent unsigned compares */
+bool SplitComparesTransform::simplifySignedness(Module &M) {
+ LLVMContext &C = M.getContext();
+ std::vector<Instruction*> icomps;
+ IntegerType *Int1Ty = IntegerType::getInt1Ty(C);
+
+ /* iterate over all functions, bbs and instruction and add
+ * all signed compares to icomps vector */
+ for (auto &F : M) {
+ for (auto &BB : F) {
+ for(auto &IN: BB) {
+ CmpInst* selectcmpInst = nullptr;
+
+ if ((selectcmpInst = dyn_cast<CmpInst>(&IN))) {
+
+ if (selectcmpInst->getPredicate() != CmpInst::ICMP_SGT &&
+ selectcmpInst->getPredicate() != CmpInst::ICMP_SLT
+ ) {
+ continue;
+ }
+
+ auto op0 = selectcmpInst->getOperand(0);
+ auto op1 = selectcmpInst->getOperand(1);
+
+ IntegerType* intTyOp0 = dyn_cast<IntegerType>(op0->getType());
+ IntegerType* intTyOp1 = dyn_cast<IntegerType>(op1->getType());
+
+ /* see above */
+ if (!intTyOp0 || !intTyOp1) {
+ continue;
+ }
+
+ /* i think this is not possible but to lazy to look it up */
+ if (intTyOp0->getBitWidth() != intTyOp1->getBitWidth()) {
+ continue;
+ }
+
+ icomps.push_back(selectcmpInst);
+ }
+ }
+ }
+ }
+
+ if (!icomps.size()) {
+ return false;
+ }
+
+ for (auto &IcmpInst: icomps) {
+ BasicBlock* bb = IcmpInst->getParent();
+
+ auto op0 = IcmpInst->getOperand(0);
+ auto op1 = IcmpInst->getOperand(1);
+
+ IntegerType* intTyOp0 = dyn_cast<IntegerType>(op0->getType());
+ unsigned bitw = intTyOp0->getBitWidth();
+ IntegerType *IntType = IntegerType::get(C, bitw);
+
+
+ /* get the new predicate */
+ auto pred = dyn_cast<CmpInst>(IcmpInst)->getPredicate();
+ CmpInst::Predicate new_pred;
+ if (pred == CmpInst::ICMP_SGT) {
+ new_pred = CmpInst::ICMP_UGT;
+ } else {
+ new_pred = CmpInst::ICMP_ULT;
+ }
+
+ BasicBlock* end_bb = bb->splitBasicBlock(BasicBlock::iterator(IcmpInst));
+
+ /* create a 1 bit compare for the sign bit. to do this shift and trunc
+ * the original operands so only the first bit remains.*/
+ Instruction *s_op0, *t_op0, *s_op1, *t_op1, *icmp_sign_bit;
+
+ s_op0 = BinaryOperator::Create(Instruction::LShr, op0, ConstantInt::get(IntType, bitw - 1));
+ bb->getInstList().insert(bb->getTerminator()->getIterator(), s_op0);
+ t_op0 = new TruncInst(s_op0, Int1Ty);
+ bb->getInstList().insert(bb->getTerminator()->getIterator(), t_op0);
+
+ s_op1 = BinaryOperator::Create(Instruction::LShr, op1, ConstantInt::get(IntType, bitw - 1));
+ bb->getInstList().insert(bb->getTerminator()->getIterator(), s_op1);
+ t_op1 = new TruncInst(s_op1, Int1Ty);
+ bb->getInstList().insert(bb->getTerminator()->getIterator(), t_op1);
+
+ /* compare of the sign bits */
+ icmp_sign_bit = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ, t_op0, t_op1);
+ bb->getInstList().insert(bb->getTerminator()->getIterator(), icmp_sign_bit);
+
+ /* create a new basic block which is executed if the signedness bit is
+ * different */
+ Instruction *icmp_inv_sig_cmp;
+ BasicBlock* sign_bb = BasicBlock::Create(C, "sign", end_bb->getParent(), end_bb);
+ if (pred == CmpInst::ICMP_SGT) {
+ /* if we check for > and the op0 positiv and op1 negative then the final
+ * result is true. if op0 negative and op1 pos, the cmp must result
+ * in false
+ */
+ icmp_inv_sig_cmp = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_ULT, t_op0, t_op1);
+ } else {
+ /* just the inverse of the above statement */
+ icmp_inv_sig_cmp = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_UGT, t_op0, t_op1);
+ }
+ sign_bb->getInstList().push_back(icmp_inv_sig_cmp);
+ BranchInst::Create(end_bb, sign_bb);
+
+ /* create a new bb which is executed if signedness is equal */
+ Instruction *icmp_usign_cmp;
+ BasicBlock* middle_bb = BasicBlock::Create(C, "injected", end_bb->getParent(), end_bb);
+ /* we can do a normal unsigned compare now */
+ icmp_usign_cmp = CmpInst::Create(Instruction::ICmp, new_pred, op0, op1);
+ middle_bb->getInstList().push_back(icmp_usign_cmp);
+ BranchInst::Create(end_bb, middle_bb);
+
+ auto term = bb->getTerminator();
+ /* if the sign is eq do a normal unsigned cmp, else we have to check the
+ * signedness bit */
+ BranchInst::Create(middle_bb, sign_bb, icmp_sign_bit, bb);
+ term->eraseFromParent();
+
+
+ PHINode *PN = PHINode::Create(Int1Ty, 2, "");
+
+ PN->addIncoming(icmp_usign_cmp, middle_bb);
+ PN->addIncoming(icmp_inv_sig_cmp, sign_bb);
+
+ BasicBlock::iterator ii(IcmpInst);
+ ReplaceInstWithInst(IcmpInst->getParent()->getInstList(), ii, PN);
+ }
+
+ return true;
+}
+
+/* splits icmps of size bitw into two nested icmps with bitw/2 size each */
+bool SplitComparesTransform::splitCompares(Module &M, unsigned bitw) {
+ LLVMContext &C = M.getContext();
+
+ IntegerType *Int1Ty = IntegerType::getInt1Ty(C);
+ IntegerType *OldIntType = IntegerType::get(C, bitw);
+ IntegerType *NewIntType = IntegerType::get(C, bitw / 2);
+
+ std::vector<Instruction*> icomps;
+
+ if (bitw % 2) {
+ return false;
+ }
+
+ /* not supported yet */
+ if (bitw > 64) {
+ return false;
+ }
+
+ /* get all EQ, NE, UGT, and ULT icmps of width bitw. if the other two
+ * unctions were executed only these four predicates should exist */
+ for (auto &F : M) {
+ for (auto &BB : F) {
+ for(auto &IN: BB) {
+ CmpInst* selectcmpInst = nullptr;
+
+ if ((selectcmpInst = dyn_cast<CmpInst>(&IN))) {
+
+ if(selectcmpInst->getPredicate() != CmpInst::ICMP_EQ &&
+ selectcmpInst->getPredicate() != CmpInst::ICMP_NE &&
+ selectcmpInst->getPredicate() != CmpInst::ICMP_UGT &&
+ selectcmpInst->getPredicate() != CmpInst::ICMP_ULT
+ ) {
+ continue;
+ }
+
+ auto op0 = selectcmpInst->getOperand(0);
+ auto op1 = selectcmpInst->getOperand(1);
+
+ IntegerType* intTyOp0 = dyn_cast<IntegerType>(op0->getType());
+ IntegerType* intTyOp1 = dyn_cast<IntegerType>(op1->getType());
+
+ if (!intTyOp0 || !intTyOp1) {
+ continue;
+ }
+
+ /* check if the bitwidths are the one we are looking for */
+ if (intTyOp0->getBitWidth() != bitw || intTyOp1->getBitWidth() != bitw) {
+ continue;
+ }
+
+ icomps.push_back(selectcmpInst);
+ }
+ }
+ }
+ }
+
+ if (!icomps.size()) {
+ return false;
+ }
+
+ for (auto &IcmpInst: icomps) {
+ BasicBlock* bb = IcmpInst->getParent();
+
+ auto op0 = IcmpInst->getOperand(0);
+ auto op1 = IcmpInst->getOperand(1);
+
+ auto pred = dyn_cast<CmpInst>(IcmpInst)->getPredicate();
+
+ BasicBlock* end_bb = bb->splitBasicBlock(BasicBlock::iterator(IcmpInst));
+
+ /* create the comparison of the top halfs of the original operands */
+ Instruction *s_op0, *op0_high, *s_op1, *op1_high, *icmp_high;
+
+ s_op0 = BinaryOperator::Create(Instruction::LShr, op0, ConstantInt::get(OldIntType, bitw / 2));
+ bb->getInstList().insert(bb->getTerminator()->getIterator(), s_op0);
+ op0_high = new TruncInst(s_op0, NewIntType);
+ bb->getInstList().insert(bb->getTerminator()->getIterator(), op0_high);
+
+ s_op1 = BinaryOperator::Create(Instruction::LShr, op1, ConstantInt::get(OldIntType, bitw / 2));
+ bb->getInstList().insert(bb->getTerminator()->getIterator(), s_op1);
+ op1_high = new TruncInst(s_op1, NewIntType);
+ bb->getInstList().insert(bb->getTerminator()->getIterator(), op1_high);
+
+ icmp_high = CmpInst::Create(Instruction::ICmp, pred, op0_high, op1_high);
+ bb->getInstList().insert(bb->getTerminator()->getIterator(), icmp_high);
+
+ /* now we have to destinguish between == != and > < */
+ if (pred == CmpInst::ICMP_EQ || pred == CmpInst::ICMP_NE) {
+ /* transformation for == and != icmps */
+
+ /* create a compare for the lower half of the original operands */
+ Instruction *op0_low, *op1_low, *icmp_low;
+ BasicBlock* cmp_low_bb = BasicBlock::Create(C, "injected", end_bb->getParent(), end_bb);
+
+ op0_low = new TruncInst(op0, NewIntType);
+ cmp_low_bb->getInstList().push_back(op0_low);
+
+ op1_low = new TruncInst(op1, NewIntType);
+ cmp_low_bb->getInstList().push_back(op1_low);
+
+ icmp_low = CmpInst::Create(Instruction::ICmp, pred, op0_low, op1_low);
+ cmp_low_bb->getInstList().push_back(icmp_low);
+ BranchInst::Create(end_bb, cmp_low_bb);
+
+ /* dependant on the cmp of the high parts go to the end or go on with
+ * the comparison */
+ auto term = bb->getTerminator();
+ if (pred == CmpInst::ICMP_EQ) {
+ BranchInst::Create(cmp_low_bb, end_bb, icmp_high, bb);
+ } else {
+ /* CmpInst::ICMP_NE */
+ BranchInst::Create(end_bb, cmp_low_bb, icmp_high, bb);
+ }
+ term->eraseFromParent();
+
+ /* create the PHI and connect the edges accordingly */
+ PHINode *PN = PHINode::Create(Int1Ty, 2, "");
+ PN->addIncoming(icmp_low, cmp_low_bb);
+ if (pred == CmpInst::ICMP_EQ) {
+ PN->addIncoming(ConstantInt::get(Int1Ty, 0), bb);
+ } else {
+ /* CmpInst::ICMP_NE */
+ PN->addIncoming(ConstantInt::get(Int1Ty, 1), bb);
+ }
+
+ /* replace the old icmp with the new PHI */
+ BasicBlock::iterator ii(IcmpInst);
+ ReplaceInstWithInst(IcmpInst->getParent()->getInstList(), ii, PN);
+
+ } else {
+ /* CmpInst::ICMP_UGT and CmpInst::ICMP_ULT */
+ /* transformations for < and > */
+
+ /* create a basic block which checks for the inverse predicate.
+ * if this is true we can go to the end if not we have to got to the
+ * bb which checks the lower half of the operands */
+ Instruction *icmp_inv_cmp, *op0_low, *op1_low, *icmp_low;
+ BasicBlock* inv_cmp_bb = BasicBlock::Create(C, "inv_cmp", end_bb->getParent(), end_bb);
+ if (pred == CmpInst::ICMP_UGT) {
+ icmp_inv_cmp = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_ULT, op0_high, op1_high);
+ } else {
+ icmp_inv_cmp = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_UGT, op0_high, op1_high);
+ }
+ inv_cmp_bb->getInstList().push_back(icmp_inv_cmp);
+
+ auto term = bb->getTerminator();
+ term->eraseFromParent();
+ BranchInst::Create(end_bb, inv_cmp_bb, icmp_high, bb);
+
+ /* create a bb which handles the cmp of the lower halfs */
+ BasicBlock* cmp_low_bb = BasicBlock::Create(C, "injected", end_bb->getParent(), end_bb);
+ op0_low = new TruncInst(op0, NewIntType);
+ cmp_low_bb->getInstList().push_back(op0_low);
+ op1_low = new TruncInst(op1, NewIntType);
+ cmp_low_bb->getInstList().push_back(op1_low);
+
+ icmp_low = CmpInst::Create(Instruction::ICmp, pred, op0_low, op1_low);
+ cmp_low_bb->getInstList().push_back(icmp_low);
+ BranchInst::Create(end_bb, cmp_low_bb);
+
+ BranchInst::Create(end_bb, cmp_low_bb, icmp_inv_cmp, inv_cmp_bb);
+
+ PHINode *PN = PHINode::Create(Int1Ty, 3);
+ PN->addIncoming(icmp_low, cmp_low_bb);
+ PN->addIncoming(ConstantInt::get(Int1Ty, 1), bb);
+ PN->addIncoming(ConstantInt::get(Int1Ty, 0), inv_cmp_bb);
+
+ BasicBlock::iterator ii(IcmpInst);
+ ReplaceInstWithInst(IcmpInst->getParent()->getInstList(), ii, PN);
+ }
+ }
+ return true;
+}
+
+bool SplitComparesTransform::runOnModule(Module &M) {
+ int bitw = 64;
+
+ char* bitw_env = getenv("LAF_SPLIT_COMPARES_BITW");
+ if (bitw_env) {
+ bitw = atoi(bitw_env);
+ }
+
+ simplifyCompares(M);
+
+ simplifySignedness(M);
+
+ errs() << "Split-compare-pass by laf.intel@gmail.com\n";
+
+ switch (bitw) {
+ case 64:
+ errs() << "Running split-compare-pass " << 64 << "\n";
+ splitCompares(M, 64);
+
+ [[clang::fallthrough]];
+ /* fallthrough */
+ case 32:
+ errs() << "Running split-compare-pass " << 32 << "\n";
+ splitCompares(M, 32);
+
+ [[clang::fallthrough]];
+ /* fallthrough */
+ case 16:
+ errs() << "Running split-compare-pass " << 16 << "\n";
+ splitCompares(M, 16);
+ break;
+
+ default:
+ errs() << "NOT Running split-compare-pass \n";
+ return false;
+ break;
+ }
+
+ verifyModule(M);
+ return true;
+}
+
+static void registerSplitComparesPass(const PassManagerBuilder &,
+ legacy::PassManagerBase &PM) {
+ PM.add(new SplitComparesTransform());
+}
+
+static RegisterStandardPasses RegisterSplitComparesPass(
+ PassManagerBuilder::EP_OptimizerLast, registerSplitComparesPass);
+
+static RegisterStandardPasses RegisterSplitComparesTransPass0(
+ PassManagerBuilder::EP_EnabledOnOptLevel0, registerSplitComparesPass);
diff -urN ./llvm_mode/split-switches-pass.so.cc ./llvm_mode/split-switches-pass.so.cc
--- ./llvm_mode/split-switches-pass.so.cc 1970-01-01 01:00:00.000000000 +0100
+++ ./llvm_mode/split-switches-pass.so.cc 2019-01-08 17:17:23.073227728 +0100
@@ -0,0 +1,315 @@
+/*
+ * Copyright 2016 laf-intel
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <unistd.h>
+
+#include "llvm/ADT/Statistic.h"
+#include "llvm/IR/IRBuilder.h"
+#include "llvm/IR/LegacyPassManager.h"
+#include "llvm/IR/Module.h"
+#include "llvm/Support/Debug.h"
+#include "llvm/Support/raw_ostream.h"
+#include "llvm/Transforms/IPO/PassManagerBuilder.h"
+#include "llvm/Transforms/Utils/BasicBlockUtils.h"
+#include "llvm/IR/Verifier.h"
+#include "llvm/Pass.h"
+#include "llvm/Analysis/ValueTracking.h"
+
+#include <set>
+
+using namespace llvm;
+
+namespace {
+
+ class SplitSwitchesTransform : public ModulePass {
+
+ public:
+ static char ID;
+ SplitSwitchesTransform() : ModulePass(ID) {
+ }
+
+ bool runOnModule(Module &M) override;
+
+#if __clang_major__ >= 4
+ StringRef getPassName() const override {
+#else
+ const char * getPassName() const override {
+#endif
+ return "splits switch constructs";
+ }
+ struct CaseExpr {
+ ConstantInt* Val;
+ BasicBlock* BB;
+
+ CaseExpr(ConstantInt *val = nullptr, BasicBlock *bb = nullptr) :
+ Val(val), BB(bb) { }
+ };
+
+ typedef std::vector<CaseExpr> CaseVector;
+
+ private:
+ bool splitSwitches(Module &M);
+ bool transformCmps(Module &M, const bool processStrcmp, const bool processMemcmp);
+ BasicBlock* switchConvert(CaseVector Cases, std::vector<bool> bytesChecked,
+ BasicBlock* OrigBlock, BasicBlock* NewDefault,
+ Value* Val, unsigned level);
+ };
+
+}