-
Notifications
You must be signed in to change notification settings - Fork 53
/
run_gen.py
executable file
·1782 lines (1542 loc) · 75 KB
/
run_gen.py
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
#!/usr/bin/python3
###############################################################################
#
# Copyright (c) 2015-2020, Intel Corporation
# Copyright (c) 2019-2020, University of Utah
#
# 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.
#
###############################################################################
"""
Script for autonomous testing with YARP Generator
"""
###############################################################################
import argparse
import datetime
import logging
import math
import multiprocessing
import multiprocessing.managers
import os
import platform
import re
import shutil
import stat
import sys
import time
import queue
import common
import gen_test_makefile
import blame_opt
res_dir = "result"
process_dir = "process_"
creduce_bin = "creduce"
creduce_n = 0
clang_total_stmt_str = "stmts/expr"
yarpgen_timeout = 60
compiler_timeout = 1200
run_timeout = 300
stat_update_delay = 10
tmp_cleanup_delay = 3600
creduce_timeout = 3600 * 24
# Various memory limits (in kbytes), passed to ulimit -v
yarpgen_mem_limit = 2000000 # 2 Gb
compiler_mem_limit = 10000000 # 10 Gb
script_start_time = datetime.datetime.now() # We should init variable, so let's do it this way
known_build_fails = { \
# clang
"Assertion `NodeToMatch\-\>getOpcode\(\) != ISD::DELETED_NODE && \"NodeToMatch was removed partway through selection\"'": "SelectionDAGISel", \
"replaceAllUses of value with new value of different type": "replaceAllUses", \
"Concatenation of vectors with inconsistent value types": "FoldCONCAT_VECTORS", \
"Integer type overpromoted": "PromoteIntRes_SETCC", \
"Cannot select.*urem": "Cannot_select_urem", \
"Cannot select.*X86ISD::PCMPEQ": "Cannot_select_pcmpeq", \
"Binary operator types must match": "Binary_operator_types_must_match", \
"Deleted Node added to Worklist": "DAGCombiner_AddToWorklist", \
"Invalid child # of SDNode": "SDNode_getOperand", \
"DELETED_NODE in CSEMap!": "DELETED_NODE_CSEMap", \
"The number of nodes scheduled doesn't match the expected number": "VerifyScheduledSequence", \
"Cannot emit physreg copy instruction": "physreg_copy", \
"Deleted edge still exists in the CFG": "deleted_cfg_edge", \
"Cannot convert from scalar to/from vector": "vec_convert", \
"Invalid constantexpr cast!": "constexpr_cast", \
# gcc
"compute_live_loop_exits": "compute_live_loop_exits", \
"ubsan_instrument_division": "ubsan_instrument_division", \
"non-trivial conversion at assignment": "verify_gimple_assignment", \
"type mismatch in shift expression": "verify_gimple_shift", \
"type mismatch in binary expression": "verify_gimple_binary", \
"REG_BR_PROB does not match": "REG_BR_PROB", \
"in build_low_bits_mask": "build_low_bits_mask", \
"non-trivial conversion in unary operation": "verify_gimple_conversion_in_unary", \
"conversion of register to a different size": "verify_gimple_register_size", \
"in decompose": "decompose", \
"mismatching comparison operand types": "verify_gimple_unary_conversion", \
"qsort checking failed": "qsort", \
"in immed_wide_int_const, at emit-rtl.c": "immed_wide_int_const", \
"during RTL pass: cprop": "cprop", \
"may be used uninitialized in this function": "may_be_uninit", \
"hoist_memory_references": "hoist_memory_references", \
"verify_gimple_in_cfg": "verify_gimple_in_cfg", \
"crash_signal": "crash_signal", \
"maybe_canonicalize_mem_ref_addr": "maybe_canonicalize_mem_ref_addr",\
# problem with available memory
"bad_alloc": "memory_problem", \
"out of memory": "memory_problem", \
"Out of memory": "memory_problem", \
"Cannot allocate memory": "memory_problem", \
"Killed": "killed", \
"relocation truncated to fit": "inp_alloc_problem", \
}
known_runtime_fails = {\
#dpcpp
"Total size of kernel arguments exceeds limit": "kernel_size",\
"CL_DEVICE_NOT_FOUND": "device_not_found",\
"Killed": "killed",\
"Aborted": "aborted",\
}
###############################################################################
class MyManager(multiprocessing.managers.BaseManager):
pass
def manager():
m = MyManager()
m.start()
return m
total = "total"
ok = "ok"
runfail = "runfail"
runfail_timeout = "runfail_timeout"
compfail = "compfail"
compfail_timeout = "compfail_timeout"
out_dif = "different_output"
class StatsParser(object):
"""All parsers should return obtained data in form of list of tuples:
[(opt_name#1, value#1), (opt_name#2, value#2),...]"""
@staticmethod
def parse_clang_opt_stats_file(inp_file_name):
common.log_msg(logging.DEBUG, "Parsing optimization statistics file: " + inp_file_name)
inp_file = common.check_and_open_file(inp_file_name, 'r')
result = []
for i in inp_file:
if ": " in i:
opt_stats_line = i.lstrip()
opt_stats_line = opt_stats_line.replace("\"", "")
opt_stats_line = opt_stats_line.replace(",", "")
opt_stats_line = opt_stats_line.replace(":", "")
opt_stats_list = opt_stats_line.split()
opt_name = opt_stats_list[0]
opt_value = int(opt_stats_list[1])
result.append((opt_name, opt_value))
common.log_msg(logging.DEBUG, "Finished parsing of optimization statistics file: " + inp_file_name)
inp_file.close()
return result
@staticmethod
def parse_clang_stmt_stats_file(inp_str):
common.log_msg(logging.DEBUG, "Parsing statement statistics")
inp_str_list = inp_str.split("\n")
result = []
for i in range(len(inp_str_list)):
if inp_str_list[i] == "*** Stmt/Expr Stats:":
i += 1
while not inp_str_list[i].startswith("Total bytes"):
stmt_stat_str = inp_str_list[i].lstrip().split()
stmt_stat_name = stmt_stat_str[1][:-1]
stmtstat_value = int(stmt_stat_str[0])
result.append((stmt_stat_name, stmtstat_value))
i += 1
common.log_msg(logging.DEBUG, "Finished parsing statement statistics")
return result
# class representing the test
class Test(object):
# list of files
# seed, string
# generator's logs
# generation time
# return code
# is time_expired
# path
# process number for logging
# status values
STATUS_ok=1
STATUS_fail=2
STATUS_fail_timeout=3
STATUS_miscompare=4
STATUS_multiple_miscompare=5
STATUS_no_good_runs=6
# Static variables
# Don't save anything other than log-file if compile time expires
ignore_comp_time_exp = True
# Generate new test
# stat is statistics object
# seed is optional, if we want to generate some particular seed.
# proc_num is optional debug info to track in what process we are running this activity.
def __init__(self, stat, seed="", proc_num=-1, blame=False, creduce_makefile=None):
# Run generator
yarpgen_run_list = [".." + os.sep + "yarpgen",
"--std=" + common.StdID.get_pretty_std_name(common.selected_standard)]
if seed:
yarpgen_run_list += ["-s", seed]
self.yarpgen_cmd = " ".join(str(p) for p in yarpgen_run_list)
self.ret_code, self.stdout, self.stderr, self.is_time_expired, self.elapsed_time = \
common.run_cmd(yarpgen_run_list, yarpgen_timeout, proc_num, yarpgen_mem_limit)
# Files that belongs to generate test. They are hardcoded for now.
# Generator may report them in output later and we may need to parse it.
self.files = gen_test_makefile.sources.value.split() + gen_test_makefile.headers.value.split()
self.files.append(gen_test_makefile.Test_Makefile_name)
# Parse generated seed.
if not seed:
if self.stdout:
seed = str(self.stdout, "utf-8").split()[1][:-2]
else:
seed = str(proc_num) + "_" + datetime.datetime.now().strftime('%Y_%m_%d_%H_%M_%S')
self.seed = seed
self.path = os.getcwd()
self.proc_num = proc_num
self.stat = stat
self.blame = blame
self.blame_phase = ""
self.blame_result = "was not run"
self.creduce = bool(creduce_makefile)
self.creduce_makefile = creduce_makefile
# Update statistics and set the status
stat.update_yarpgen_duration(datetime.timedelta(seconds=self.elapsed_time))
if self.is_time_expired:
common.log_msg(logging.WARNING, "Generator has failed (" + runfail_timeout + ")")
self.status = self.STATUS_fail_timeout
stat.update_yarpgen_runs(runfail)
self.stat.seed_failed(self.seed)
elif self.ret_code != 0:
common.log_msg(logging.WARNING, "Generator has failed (" + runfail + ")")
self.status = self.STATUS_fail
stat.update_yarpgen_runs(runfail)
self.stat.seed_failed(self.seed)
else:
self.status = self.STATUS_ok
stat.update_yarpgen_runs(ok)
# Initialize set of test runs
self.successful_test_runs = []
self.fail_test_runs = []
seed_file = open("seed", "w")
seed_file.write(self.seed + "\n")
seed_file.close()
common.log_msg(logging.DEBUG, "Process " + str(proc_num) + " has generated seed " + str(seed))
# Check status
def is_ok(self):
return self.status == self.STATUS_ok
def status_string(self):
if self.status == self.STATUS_ok: return "ok"
elif self.status == self.STATUS_fail: return "gen_fail"
elif self.status == self.STATUS_fail_timeout: return "gen_fail_timeout"
elif self.status == self.STATUS_miscompare: return "miscompare"
elif self.status == self.STATUS_multiple_miscompare: return "multiple_miscompare"
elif self.status == self.STATUS_no_good_runs: return "no_good_runs"
else: raise
# Save test
def save(self, lock):
if self.status != self.STATUS_fail_timeout and self.status != self.STATUS_fail:
raise
log = self.build_log()
save_test(lock, file_list=[log],
compiler_name=None,
fail_type=self.status_string(),
classification=None,
test_name=None)
# Add successful test run
def add_success_run(self, test_run):
self.successful_test_runs.append(test_run)
# Add fail test run
def add_fail_run(self, test_run):
self.fail_test_runs.append(test_run)
# Save failed runs and verify successful runs
def handle_results(self, lock):
# Handle compfails and runfails.
self.save_failed(lock)
# Handle miscompares.
self.verify_results(lock)
if self.status == self.STATUS_ok and len(self.fail_test_runs) == 0:
self.stat.seed_passed(self.seed)
else:
self.stat.seed_failed(self.seed)
# Save failed runs.
# Report fails of the same type together.
def save_failed(self, lock):
build_fail = None
run_fail = None
for run in self.fail_test_runs:
if run.status == TestRun.STATUS_compfail or \
run.status == TestRun.STATUS_compfail_timeout:
if build_fail:
build_fail.same_type_fails.append(run)
else:
build_fail = run
elif run.status == TestRun.STATUS_runfail or \
run.status == TestRun.STATUS_runfail_timeout:
if run_fail:
run_fail.same_type_fails.append(run)
else:
run_fail = run
else:
raise
if build_fail:
if self.creduce:
self.do_creduce_buildfail(build_fail)
build_fail.save(lock)
if run_fail:
# Do blaming if blame switch is passed, there are successful runs and fail is not a timeout.
if self.blame and len(self.successful_test_runs) > 0 and run_fail.status == TestRun.STATUS_runfail:
do_blame(run_fail, self.files, self.successful_test_runs[0].checksum, run_fail.target)
if self.creduce:
self.do_creduce_runfail(run_fail)
run_fail.save(lock)
# Verify the results and if bad results are found, report / save them.
def verify_results(self, lock):
results = {}
for t in self.successful_test_runs:
assert t.status == TestRun.STATUS_ok
if t.checksum not in results:
results[t.checksum] = [t]
else:
results[t.checksum].append(t)
# Check if test passed.
if len(results) == 1 and not "ERROR" in next(iter(results)):
return
elif len(results) == 2:
self.status = self.STATUS_miscompare
runs = list(results.values())
good_runs = runs[0]
bad_runs = runs[1]
# Majority vote
if len(bad_runs) > len(good_runs):
good_runs, bad_runs = bad_runs, good_runs
# Count number of no_opt optsets in each bin.
good_no_opt = 0
for run in good_runs:
good_no_opt += run.optset.count("no_opt")
bad_no_opt = 0
for run in bad_runs:
bad_no_opt += run.optset.count("no_opt")
if good_no_opt == 0 and bad_no_opt > 0:
good_runs, bad_runs = bad_runs, good_runs
# Assume one compiler is failing at many opt-sets.
good_cmplrs = set()
bad_cmplrs = set()
for run in good_runs:
good_cmplrs.add(run.target.specs.name)
for run in bad_runs:
bad_cmplrs.add(run.target.specs.name)
if len(good_cmplrs) < len(bad_cmplrs):
good_runs, bad_runs = bad_runs, good_runs
else:
# More than 2 different results.
# Treat them all as bad
if len(results) == 0:
self.status = self.STATUS_no_good_runs
else:
self.status = self.STATUS_multiple_miscompare
good_runs = []
bad_runs = []
for run in results.values():
bad_runs += run
# Run blame triaging for one of failing optsets
if self.blame and good_runs:
do_blame(self, self.files, good_runs[0].checksum, bad_runs[0].target)
# Run creduce for one of failing optsets
if self.creduce and good_runs:
self.do_creduce_miscompare(good_runs, bad_runs)
# Report
for run in bad_runs:
self.stat.update_target_runs(run.optset, out_dif)
# Build log
log = self.build_log(bad_runs, good_runs)
self.files.append(log)
# List of files to save
files_to_save = self.files
for run in (bad_runs + good_runs):
files_to_save.append(run.exe_file)
# Prepare compiler's name set
cmplr_set = set()
for run in bad_runs:
cmplr_set.add(run.target.specs.name)
cmplr_set = list(cmplr_set)
cmplr_set.sort()
cmplr = "-".join(c for c in cmplr_set)
blame_phase = None
if len(self.blame_phase) != 0:
blame_phase = self.blame_phase.replace(" ", "_")
save_test(lock, files_to_save,
compiler_name = cmplr,
fail_type = self.status_string(),
classification = blame_phase,
test_name = "S_" + str(self.seed))
def build_log(self, bad_runs=[], good_runs=[]):
log_name = "log.txt"
log = open(log_name, "w")
log.write("YARPGEN version: " + common.yarpgen_version_str + "\n")
log.write("Seed: " + str(self.seed) + "\n")
log.write("Time: " + datetime.datetime.now().strftime('%Y/%m/%d %H:%M:%S') + "\n")
log.write("Language standard: " + common.get_standard() + "\n")
log.write("Type: " + self.status_string() + "\n")
if self.blame:
log.write("Blaming " + self.blame_result + "\n")
log.write("Optimization to blame: " + self.blame_phase + "\n")
log.write("\n\n")
if self.status == self.STATUS_fail_timeout:
log.write("Generator timeout: " + str(yarpgen_timeout) + " seconds\n")
if self.status == self.STATUS_fail or self.status == self.STATUS_fail_timeout:
log.write("Generator cmd: " + self.yarpgen_cmd + "\n")
log.write("Generator exit code: " + str(self.ret_code) + "\n")
log.write("=== Generator log ==================================================\n")
log.write(str(self.stdout, "utf-8"))
log.write("=== Generator err ==================================================\n")
log.write(str(self.stderr, "utf-8"))
log.write("=== Generator end ==================================================\n")
log.write("\n")
if self.status >= self.STATUS_miscompare:
log.write("==== FAILED TEST RUNS =====================\n")
for run in self.fail_test_runs:
log.write("Optset " + run.optset + " has status " + run.status_string() + "\n")
log.write("==== SUCCESSFUL TEST RUNS =================\n")
for run in self.successful_test_runs:
log.write("Optset " + run.optset + " has status " + run.status_string() + "\n")
if self.status == self.STATUS_no_good_runs:
log.write("===========================================\n")
log.write("For details look for this fail saved as one of individual compfail or runfail")
else:
for run in bad_runs:
log.write("==== BAD ==================================\n")
log.write("Optset: " + run.optset + "\n")
log.write("Output: " + str(run.run_stdout, "utf-8") + "\n")
log.write("===========================================\n\n")
for run in good_runs:
log.write("==== GOOD =================================\n")
log.write("Optset: " + run.optset + "\n")
log.write("Output: " + str(run.run_stdout, "utf-8") + "\n")
log.write("===========================================\n")
log.close()
return log_name
def creduce_performance_hack(self):
# 1. Move iostream include to driver.cpp
# 2. Remove array, vector and valarray if the are not used
init_h = open("init.h")
init_h_content = init_h.read()
init_h.close()
func_cpp = open("func.cpp")
func_cpp_content = func_cpp.read()
func_cpp.close()
iostream = re.compile("iostream")
array = re.compile("std::array")
vector = re.compile("std::vector")
valarray = re.compile("std::valarray")
remove_iostream = len(iostream.findall(init_h_content)) != 0
remove_array = len(array.findall(init_h_content)) == 0 and \
len(array.findall(func_cpp_content)) == 0
remove_vector = len(vector.findall(init_h_content)) == 0 and \
len(vector.findall(func_cpp_content)) == 0
remove_valarray = len(valarray.findall(init_h_content)) == 0 and \
len(valarray.findall(func_cpp_content)) == 0
if remove_iostream:
driver_cpp = open("driver.cpp")
driver_cpp_content = driver_cpp.read()
driver_cpp.close()
driver_cpp = open("driver.cpp", "w")
driver_cpp.write("#include <iostream>\n")
driver_cpp.write(driver_cpp_content)
driver_cpp.close()
if remove_iostream or remove_array or remove_vector or remove_valarray:
init_h = open("init.h")
init_h_content = init_h.readlines()
init_h.close()
init_h = open("init.h", "w")
for l in init_h_content:
if not (remove_iostream and re.search("\<iostream\>", l) or \
remove_array and re.search("\<array\>", l) or \
remove_vector and re.search("\<vector\>", l) or \
remove_valarray and re.search("\<valarray\>", l)):
init_h.write(l)
init_h.close()
def check_for_creduce_fails(self):
found_bugs = False
for entry in os.listdir():
if os.path.basename(entry).startswith('creduce_bug') and os.path.isdir(entry):
common.check_and_copy(entry, "..")
self.files.append(entry)
found_bugs = True
if found_bugs:
common.log_msg(logging.INFO, "\nCReduce for seed " + self.seed + " got an error, consider reporting the bug.\n" +
"Check for creduce_bug_000 dir in the results.", forced_duplication=True)
#TODO: all do_creduce _* function have a lot of copy-pasted code. We need to refactor them!
def do_creduce_miscompare(self, good_runs, bad_runs):
# Pick the fastest non-failing opt-set
good_run = None
good_time = 0
for run in good_runs:
if not run.target.specs.name.startswith("ubsan"):
continue
time = run.build_elapsed_time + run.run_elapsed_time
if good_run is None or time < good_time:
good_run, good_time = run, time
if not good_run:
# TODO: fix
common.log_msg(logging.WARNING, "No good UBSAN runs found for seed " + self.seed + \
" in process " + str(self.proc_num), True)
common.log_msg(logging.WARNING, "PLEASE CHECK THAT UBSAN IS IN YOUR TARGETS!", True)
raise
bad_run = None
bad_time = 0
for run in bad_runs:
time = run.build_elapsed_time + run.run_elapsed_time
if bad_run is None or time < bad_time:
bad_run, bad_time = run, time
common.log_msg(logging.DEBUG, "Running creduce for seed " + self.seed + ": " + \
good_run.optset + " vs " + bad_run.optset)
# Prepare Makefile
common.check_and_copy(self.creduce_makefile, ".")
creduce_makefile_name = os.path.basename(self.creduce_makefile)
self.files.append(creduce_makefile_name)
# Prepare reduce folder
os.mkdir("reduce")
for f in self.files:
common.check_and_copy(f, "reduce")
os.chdir("reduce")
# This is required only for old loop code and assumes 5 files, not 2.
#self.creduce_performance_hack()
# Now we need to construct a Makefile and script for passing to creduce.
# Need to make sure that -Werror=uninitialized is passed to the compiler.
# Recommended flags:
# -O0 -fsanitize=undefined -fno-sanitize-recover=undefined -w -Werror=uninitialized
test_sh = "#!/bin/bash\n\n"
test_sh +="ulimit -t " + str(max(compiler_timeout, run_timeout)) + "\n\n"
test_sh +="export TEST_PWD="+os.getcwd()+"\n\n"
test_sh +="make -f $TEST_PWD" + os.sep + creduce_makefile_name + " " + good_run.optset + " &&\\\n"
test_sh +="make -f $TEST_PWD" + os.sep + creduce_makefile_name + " run_" + good_run.optset + " > no_opt_out &&\\\n"
test_sh +="make -f $TEST_PWD" + os.sep + creduce_makefile_name + " " + bad_run.optset + " &&\\\n"
test_sh +="make -f $TEST_PWD" + os.sep + creduce_makefile_name + " run_" + bad_run.optset + " > opt_out &&\\\n"
test_sh +="! diff no_opt_out opt_out"
test_sh_file = open("test.sh", "w")
test_sh_file.write(test_sh)
test_sh_file.close()
st = os.stat(test_sh_file.name)
os.chmod(test_sh_file.name, st.st_mode | stat.S_IEXEC)
common.check_and_copy(test_sh_file.name, "..")
self.files.append(test_sh_file.name)
# Run creduce
cr_params_list = [creduce_bin, "--n", str(creduce_n), "--timing", "--timeout",
str((run_timeout+compiler_timeout)*2), os.path.abspath(test_sh_file.name),
common.append_file_ext("func")]
cr_ret_code, cr_stdout, cr_stderr, cr_is_time_expired, cr_elapsed_time = \
common.run_cmd(cr_params_list, creduce_timeout, self.proc_num)
# Store results and copy them back
cr_out = open("creduce_" + bad_run.optset + ".out", "w")
cr_out.write(str(cr_stdout, "utf-8"))
cr_out.close()
common.check_and_copy(cr_out.name, "..")
self.files.append(cr_out.name)
cr_err = open("creduce_" + bad_run.optset + ".err", "w")
cr_err.write(str(cr_stderr, "utf-8"))
cr_err.close()
common.check_and_copy(cr_err.name, "..")
self.files.append(cr_err.name)
cr_log = open("creduce_" + bad_run.optset + ".log", "w")
cr_log.write("Return code: " + str(cr_ret_code) + "\n")
cr_log.write("Execution time: " + str(cr_elapsed_time) + "\n")
cr_log.write("Time limit was exceeded!\n" if cr_is_time_expired else "Time limit was not exceeded\n")
cr_log.close()
common.check_and_copy(cr_log.name, "..")
self.files.append(cr_log.name)
reduced_file_name = common.append_file_ext("func_reduced_" + bad_run.optset)
common.check_and_copy(common.append_file_ext("func"), ".." + os.sep + reduced_file_name)
self.files.append(reduced_file_name)
self.check_for_creduce_fails()
os.chdir(self.path)
def do_creduce_buildfail(self, buildfail_run):
# Pick a ubsan run.
ubsan_run = None
ubsan_time = 0
for run in self.successful_test_runs:
if not run.target.specs.name.startswith("ubsan"):
continue
time = run.build_elapsed_time + run.run_elapsed_time
if ubsan_run is None or time < ubsan_time:
ubsan_run, ubsan_time = run, time
common.log_msg(logging.DEBUG, "Running creduce (compfail) for seed " + self.seed + ": " + \
buildfail_run.optset + " with " + (ubsan_run.optset if ubsan_run else "missing ubsan"))
if not ubsan_run:
common.log_msg(logging.WARNING, "Failed to reduce because of missing good ubsan run: seed " + \
self.seed, True)
return
# Prepare Makefile
common.check_and_copy(self.creduce_makefile, ".")
creduce_makefile_name = os.path.basename(self.creduce_makefile)
self.files.append(creduce_makefile_name)
# Prepare reduce folder
os.mkdir("reduce_compfail")
for f in self.files:
common.check_and_copy(f, "reduce_compfail")
os.chdir("reduce_compfail")
# Now we need to construct a Makefile and script for passing to creduce.
# Need to make sure that -Werror=uninitialized is passed to the compiler.
# Recommended flags:
# -O0 -fsanitize=undefined -fno-sanitize-recover=undefined -w -Werror=uninitialized
test_sh = "#!/bin/bash\n\n"
test_sh +="ulimit -t " + str(compiler_timeout) + "\n\n"
test_sh +="export TEST_PWD="+os.getcwd()+"\n\n"
test_sh +="! make -f $TEST_PWD" + os.sep + creduce_makefile_name + " " + buildfail_run.optset + " &&\\\n"
test_sh +="make -f $TEST_PWD" + os.sep + creduce_makefile_name + " " + ubsan_run.optset + " &&\\\n"
test_sh +="make -f $TEST_PWD" + os.sep + creduce_makefile_name + " run_" + ubsan_run.optset + " \n"
test_sh_file = open("test.sh", "w")
test_sh_file.write(test_sh)
test_sh_file.close()
st = os.stat(test_sh_file.name)
os.chmod(test_sh_file.name, st.st_mode | stat.S_IEXEC)
common.check_and_copy(test_sh_file.name, "..")
self.files.append(test_sh_file.name)
# Run creduce
cr_params_list = [creduce_bin, "--n", str(creduce_n), "--timing", "--timeout",
str((run_timeout+compiler_timeout)*2), os.path.abspath(test_sh_file.name),
common.append_file_ext("func")]
cr_ret_code, cr_stdout, cr_stderr, cr_is_time_expired, cr_elapsed_time = \
common.run_cmd(cr_params_list, creduce_timeout, self.proc_num)
# Store results and copy them back
cr_out = open("creduce_" + buildfail_run.optset + ".out", "w")
cr_out.write(str(cr_stdout, "utf-8"))
cr_out.close()
common.check_and_copy(cr_out.name, "..")
self.files.append(cr_out.name)
cr_err = open("creduce_" + buildfail_run.optset + ".err", "w")
cr_err.write(str(cr_stderr, "utf-8"))
cr_err.close()
common.check_and_copy(cr_err.name, "..")
self.files.append(cr_err.name)
cr_log = open("creduce_" + buildfail_run.optset + ".log", "w")
cr_log.write("Return code: " + str(cr_ret_code) + "\n")
cr_log.write("Execution time: " + str(cr_elapsed_time) + "\n")
cr_log.write("Time limit was exceeded!\n" if cr_is_time_expired else "Time limit was not exceeded\n")
cr_log.close()
common.check_and_copy(cr_log.name, "..")
self.files.append(cr_log.name)
reduced_file_name = common.append_file_ext("func_reduced_" + buildfail_run.optset)
common.check_and_copy(common.append_file_ext("func"), ".." + os.sep + reduced_file_name)
self.files.append(reduced_file_name)
self.check_for_creduce_fails()
os.chdir(self.path)
def do_creduce_runfail(self, runfail_run):
# Pick a ubsan run.
ubsan_run = None
ubsan_time = 0
for run in self.successful_test_runs:
if not run.target.specs.name.startswith("ubsan"):
continue
time = run.build_elapsed_time + run.run_elapsed_time
if ubsan_run is None or time < ubsan_time:
ubsan_run, ubsan_time = run, time
common.log_msg(logging.DEBUG, "Running creduce (runfail) for seed " + self.seed + ": " + \
runfail_run.optset + " with " + (ubsan_run.optset if ubsan_run else "missing ubsan"))
if not ubsan_run:
common.log_msg(logging.WARNING, "Failed to reduce because of missing good ubsan run: seed " + \
self.seed, True)
return
# Prepare Makefile
common.check_and_copy(self.creduce_makefile, ".")
creduce_makefile_name = os.path.basename(self.creduce_makefile)
self.files.append(creduce_makefile_name)
# Prepare reduce folder
os.mkdir("reduce_runfail")
for f in self.files:
common.check_and_copy(f, "reduce_runfail")
os.chdir("reduce_runfail")
# Now we need to construct a Makefile and script for passing to creduce.
# Need to make sure that -Werror=uninitialized is passed to the compiler.
# Recommended flags:
# -O0 -fsanitize=undefined -fno-sanitize-recover=undefined -w -Werror=uninitialized
test_sh = "#!/bin/bash\n\n"
test_sh +="ulimit -t " + str(compiler_timeout) + "\n\n"
test_sh +="export TEST_PWD="+os.getcwd()+"\n\n"
test_sh +="make -f $TEST_PWD" + os.sep + creduce_makefile_name + " " + runfail_run.optset + " && \\\n"
test_sh +="make -f $TEST_PWD" + os.sep + creduce_makefile_name + " run_" + runfail_run.optset + " 2>err.log\n"
test_sh +="RETCODE=$?\n"
test_sh +="[ $RETCODE -eq " + str(runfail_run.run_ret_code) + " ] && \\\n"
# it's "temporary" (until LLVM bug 33133 is fixed).
# This is needed when reduceing gcc_ubsan problem. Without this check we have good chances to reduce to the code
# snippet, which contains left shift of negative value (caught by gcc ubsan, but not clang ubsan).
test_sh +="! grep \"left shift of negative value\" err.log && \\\n"
test_sh +="make -f $TEST_PWD" + os.sep + creduce_makefile_name + " " + ubsan_run.optset + " && \\\n"
test_sh +="make -f $TEST_PWD" + os.sep + creduce_makefile_name + " run_" + ubsan_run.optset + " \n"
test_sh_file = open("test.sh", "w")
test_sh_file.write(test_sh)
test_sh_file.close()
st = os.stat(test_sh_file.name)
os.chmod(test_sh_file.name, st.st_mode | stat.S_IEXEC)
common.check_and_copy(test_sh_file.name, "..")
self.files.append(test_sh_file.name)
# Run creduce
cr_params_list = [creduce_bin, "--n", str(creduce_n), "--timing", "--timeout",
str((run_timeout+compiler_timeout)*2), os.path.abspath(test_sh_file.name),
common.append_file_ext("func")]
cr_ret_code, cr_stdout, cr_stderr, cr_is_time_expired, cr_elapsed_time = \
common.run_cmd(cr_params_list, creduce_timeout, self.proc_num)
# Store results and copy them back
cr_out = open("creduce_" + runfail_run.optset + ".out", "w")
cr_out.write(str(cr_stdout, "utf-8"))
cr_out.close()
common.check_and_copy(cr_out.name, "..")
self.files.append(cr_out.name)
cr_err = open("creduce_" + runfail_run.optset + ".err", "w")
cr_err.write(str(cr_stderr, "utf-8"))
cr_err.close()
common.check_and_copy(cr_err.name, "..")
self.files.append(cr_err.name)
cr_log = open("creduce_" + runfail_run.optset + ".log", "w")
cr_log.write("Return code: " + str(cr_ret_code) + "\n")
cr_log.write("Execution time: " + str(cr_elapsed_time) + "\n")
cr_log.write("Time limit was exceeded!\n" if cr_is_time_expired else "Time limit was not exceeded\n")
cr_log.close()
common.check_and_copy(cr_log.name, "..")
self.files.append(cr_log.name)
reduced_file_name = common.append_file_ext("func_reduced_" + runfail_run.optset)
common.check_and_copy(common.append_file_ext("func"), ".." + os.sep + reduced_file_name)
self.files.append(reduced_file_name)
self.check_for_creduce_fails()
os.chdir(self.path)
# End of Test class
# TODO:
# 1. save test
# 2. generate log
# 3. diagnostic logic
# 4. rerun test from the dir?
# End of Test class
# class representing the result of running a single opt-set for the test
class TestRun(object):
# opt-set
# build / execution log
# build / execution time
# run result: pass / compfail / compfail_timeout / runfail / runfail_timeout / miscompare.
# compilation log
STATUS_not_built = 1
STATUS_not_run = 2
STATUS_compfail = 3
STATUS_compfail_timeout = 4
STATUS_runfail = 5
STATUS_runfail_timeout = 6
STATUS_ok = 7
STATUS_miscompare = 8
def __init__(self, test, stat, target, proc_num=-1, parse_stats=False):
self.test = test
self.stat = stat
self.target = target
self.optset = target.name
self.proc_num = proc_num
self.status = self.STATUS_not_built
self.files = []
self.same_type_fails = []
self.blame_phase = ""
self.blame_result = "was not run"
self.parse_stats = parse_stats
# Build test
def build(self):
# build
build_params_list = ["make", "-f", gen_test_makefile.Test_Makefile_name, self.optset]
self.build_cmd = " ".join(str(p) for p in build_params_list)
self.build_ret_code, self.build_stdout, self.build_stderr, self.is_build_time_expired, self.build_elapsed_time = \
common.run_cmd(build_params_list, compiler_timeout, self.proc_num, compiler_mem_limit)
# update status and stats
if self.is_build_time_expired:
self.stat.update_target_runs(self.optset, compfail_timeout)
self.status = self.STATUS_compfail_timeout
elif self.build_ret_code != 0:
self.stat.update_target_runs(self.optset, compfail)
self.status = self.STATUS_compfail
else:
self.status = self.STATUS_not_run
# parse stats if needed
if self.parse_stats and os.path.isfile("func.stats"):
opt_stats = None
stmt_stats = None
if "clang" in self.target.specs.name:
opt_stats = StatsParser.parse_clang_opt_stats_file("func.stats")
stmt_stats = StatsParser.parse_clang_stmt_stats_file(str(self.build_stderr, "utf-8"))
self.stat.add_stats(opt_stats, self.optset, StatsVault.opt_stats_id)
self.stat.add_stats(stmt_stats, self.optset, StatsVault.stmt_stats_id)
# update file list
expected_files = [source + ".o" for source in gen_test_makefile.sources.value.split()]
expected_files.append(gen_test_makefile.executable.value)
expected_files = [self.optset + "_" + e for e in expected_files]
if self.parse_stats:
expected_files.append("func.stats")
for f in expected_files:
if os.path.isfile(f):
self.files.append(f)
# save executable separately (we need it in case of miscompare)
exe_file = self.optset + "_out"
if os.path.isfile(exe_file):
self.exe_file = exe_file
return self.status == self.STATUS_not_run
# Run test
def run(self):
# run
run_params_list = ["make", "-f", gen_test_makefile.Test_Makefile_name, "run_" + self.optset]
self.run_cmd = " ".join(str(p) for p in run_params_list)
self.run_ret_code, self.run_stdout, self.run_stderr, self.run_is_time_expired, self.run_elapsed_time = \
common.run_cmd(run_params_list, run_timeout, self.proc_num)
# update status and stats
if self.run_is_time_expired:
self.stat.update_target_runs(self.optset, runfail_timeout)
self.status = self.STATUS_runfail_timeout
elif self.run_ret_code != 0:
self.stat.update_target_runs(self.optset, runfail)
self.status = self.STATUS_runfail
else:
self.stat.update_target_runs(self.optset, ok)
self.status = self.STATUS_ok
self.checksum = str(self.run_stdout, "utf-8")
self.stat.update_target_duration(self.optset, datetime.timedelta(seconds=self.build_elapsed_time+self.run_elapsed_time))
return self.status == self.STATUS_ok
def status_string(self):
if self.status == self.STATUS_ok: return "ok"
elif self.status == self.STATUS_miscompare: return "miscompare"
elif self.status == self.STATUS_compfail: return "compfail"
elif self.status == self.STATUS_compfail_timeout: return "compfail_timeout"
elif self.status == self.STATUS_runfail: return "runfail"
elif self.status == self.STATUS_runfail_timeout: return "runfail_timeout"
elif self.status == self.STATUS_not_built: return "not_built"
elif self.status == self.STATUS_not_run: return "not_run"
else: raise
def save(self, lock):
if self.status <= self.STATUS_not_built or self.status >= self.STATUS_miscompare:
raise
save_status = self.status_string()
# TODO: it's the place to add a hook for build and run classification:
classification = None
if self.status == self.STATUS_compfail:
# classify compfail
res = self.classify_build_fail()
if res is not None:
classification = res
elif self.status == self.STATUS_runfail:
# classify runfail
# use blame info
res = self.classify_runtime_fail()
if res is not None:
classification = res
elif len(self.blame_phase) != 0:
classification = self.blame_phase.replace(" ", "_")
# Files to save: source files, own files, files from similar fails and
# log file.
file_list = []
if self.status != self.STATUS_compfail_timeout or not self.test.ignore_comp_time_exp:
file_list = self.test.files + self.files
for run in self.same_type_fails:
file_list += run.files
# Remove duplicates
file_list = list(set(file_list))
log = self.build_log()
file_list.append(log)
save_test(lock,
file_list,
compiler_name=self.target.specs.name,
fail_type=save_status,
classification=classification,
test_name="S_"+str(self.test.seed))
def classify_build_fail(self):
for reg_expr, tag in known_build_fails.items():
if re.search(reg_expr, str(self.build_stderr, "utf-8")):
return tag
return None
def classify_runtime_fail(self):
for reg_expr, tag in known_runtime_fails.items():
if re.search(reg_expr, str(self.run_stderr, "utf-8")):
return tag
return None
def build_log(self):
log_name = "log.txt"
log = open(log_name, "w")
log.write("YARPGEN version: " + common.yarpgen_version_str + "\n")
log.write("Seed: " + str(self.test.seed) + "\n")
log.write("Time: " + datetime.datetime.now().strftime('%Y/%m/%d %H:%M:%S') + "\n")
tests = [self] + self.same_type_fails
log.write("Optsets: " + ", ".join(t.optset for t in tests) + "\n")
log.write("Language standard: " + common.get_standard() + "\n")
log.write("Type: " + self.status_string() + "\n")
if self.test.blame:
log.write("Blaming " + self.blame_result + "\n")
log.write("Optimization to blame: " + self.blame_phase + "\n")
for test in tests:
log.write("\n\n")
log.write("====================================================================\n")
log.write("========== Details for " + test.optset + " optset.\n")
log.write("====================================================================\n")
if test.status == self.STATUS_compfail_timeout:
log.write("Build timeout: " + str(compiler_timeout) + " seconds\n")
if Test.ignore_comp_time_exp:
log.write("File sizes: \n")
for file in self.test.files + self.files:
size = add_metrix_prefix(os.path.getsize(file)) + "b"