├── .gitignore ├── .clang-format ├── CITATION.cff ├── .github └── workflows │ └── build.yml ├── CMakeLists.txt ├── rustlantis.py ├── emireduce.py ├── README.md ├── llubi.cpp ├── emireduce.cpp ├── csmith.py ├── LICENSE └── ubi.h /.gitignore: -------------------------------------------------------------------------------- 1 | build 2 | .vscode 3 | .cache 4 | -------------------------------------------------------------------------------- /.clang-format: -------------------------------------------------------------------------------- 1 | BasedOnStyle: LLVM 2 | IncludeCategories: 3 | - Regex: "llvm/" 4 | Priority: 1 5 | - Regex: ".*" 6 | Priority: 2 7 | -------------------------------------------------------------------------------- /CITATION.cff: -------------------------------------------------------------------------------- 1 | cff-version: 1.2.0 2 | message: "If you use this tool, please cite it as below." 3 | title: LLVM UB-Aware Interpreter 4 | type: software 5 | authors: 6 | - given-names: Yingwei 7 | family-names: Zheng 8 | email: dtcxzyw2333@gmail.com 9 | affiliation: Southern University of Science and Technology 10 | url: "https://github.com/dtcxzyw/llvm-ub-aware-interpreter" 11 | license: Apache License 2.0 12 | -------------------------------------------------------------------------------- /.github/workflows/build.yml: -------------------------------------------------------------------------------- 1 | name: Build 2 | 3 | on: 4 | schedule: 5 | - cron: "0 0 * * *" 6 | 7 | workflow_dispatch: 8 | push: 9 | pull_request: 10 | 11 | jobs: 12 | build: 13 | runs-on: ubuntu-latest 14 | 15 | steps: 16 | - name: Checkout code 17 | uses: actions/checkout@v4 18 | 19 | - name: Install dependencies (Linux) 20 | run: | 21 | wget -O- https://apt.llvm.org/llvm-snapshot.gpg.key | sudo apt-key add - 22 | sudo add-apt-repository "deb http://apt.llvm.org/noble/ llvm-toolchain-noble main" 23 | # Workaround for issue https://github.com/llvm/llvm-project/issues/133861 24 | sudo ln -s /usr/lib/llvm-22/lib /usr/lib/lib 25 | sudo ln -s /usr/lib/llvm-22/include /usr/lib/include 26 | sudo apt-get update 27 | sudo apt-get install ninja-build llvm-22-dev 28 | 29 | - name: Compile 30 | run: | 31 | mkdir -p build && cd build 32 | cmake .. -DCMAKE_BUILD_TYPE=Release -G Ninja 33 | cmake --build . -j 34 | 35 | -------------------------------------------------------------------------------- /CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 3.20) 2 | 3 | set(CMAKE_EXPORT_COMPILE_COMMANDS ON) 4 | 5 | set(CMAKE_FIND_PACKAGE_SORT_ORDER NATURAL) 6 | set(CMAKE_FIND_PACKAGE_SORT_DIRECTION DEC) 7 | 8 | set(CMAKE_CXX_STANDARD 20) 9 | set(CMAKE_CXX_STANDARD_REQUIRED ON) 10 | set(CMAKE_CXX_EXTENSIONS OFF) 11 | 12 | project(llvm-ub-aware-interpreter) 13 | 14 | find_package(LLVM REQUIRED CONFIG) 15 | message(STATUS "Found LLVM ${LLVM_PACKAGE_VERSION}") 16 | message(STATUS "Using LLVMConfig.cmake in: ${LLVM_DIR}") 17 | include(AddLLVM) 18 | 19 | include_directories(${LLVM_INCLUDE_DIRS}) 20 | set(LLVM_LINK_COMPONENTS core support irreader irprinter targetparser analysis transformutils) 21 | add_compile_options("-Wall") 22 | if (LLUBI_ENABLE_SANITIZER) 23 | add_compile_options("-ggdb") 24 | add_compile_options("-fsanitize=address,undefined") 25 | add_link_options("-fsanitize=address,undefined") 26 | endif(LLUBI_ENABLE_SANITIZER) 27 | 28 | add_llvm_library(ubi PARTIAL_SOURCES_INTENDED ubi.cpp) 29 | add_llvm_executable(llubi PARTIAL_SOURCES_INTENDED llubi.cpp) 30 | target_link_libraries(llubi PRIVATE ubi) 31 | add_llvm_executable(emireduce PARTIAL_SOURCES_INTENDED emireduce.cpp) 32 | target_link_libraries(emireduce PRIVATE ubi) 33 | -------------------------------------------------------------------------------- /rustlantis.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | from multiprocessing import Pool 4 | from tqdm import tqdm 5 | import os 6 | import sys 7 | import subprocess 8 | import shutil 9 | import tqdm 10 | import datetime 11 | import secrets 12 | 13 | # python3 ../rustlantis.py ../../LLVM/rustlantis 1 14 | 15 | rustlantis_dir = sys.argv[1] 16 | subprocess.check_call(["cargo", "build", "--release"], cwd=rustlantis_dir) 17 | test_count = int(sys.argv[2]) 18 | generate = os.path.join(rustlantis_dir, "target/release/generate") 19 | difftest = os.path.join(rustlantis_dir, "target/release/difftest") 20 | timeout = 30.0 21 | 22 | cwd = "rustlantis" + datetime.datetime.now().strftime("%Y-%m-%d@%H:%M") 23 | os.makedirs(cwd) 24 | 25 | 26 | def rustlantis_test(i): 27 | seed = secrets.randbelow(2**64) 28 | basename = cwd + "/test" + str(i) + "_" + hex(seed)[2:] 29 | file_rs = basename + ".rs" 30 | try: 31 | with open(file_rs, "w") as f: 32 | subprocess.check_call( 33 | [generate, str(seed)], 34 | timeout=timeout, 35 | stdout=f, 36 | stderr=subprocess.DEVNULL, 37 | ) 38 | except subprocess.SubprocessError: 39 | if os.path.exists(file_rs): 40 | os.remove(file_rs) 41 | return None 42 | 43 | try: 44 | subprocess.check_call( 45 | [difftest, file_rs], 46 | timeout=timeout, 47 | stdout=subprocess.DEVNULL, 48 | stderr=subprocess.DEVNULL, 49 | ) 50 | except subprocess.SubprocessError: 51 | return False 52 | os.remove(file_rs) 53 | return True 54 | 55 | 56 | L = list(range(test_count)) 57 | pbar = tqdm.tqdm(L) 58 | error_count = 0 59 | skipped_count = 0 60 | pool = Pool(os.cpu_count()) 61 | 62 | for res in pool.imap_unordered(rustlantis_test, L): 63 | if res is not None: 64 | error_count += 0 if res else 1 65 | else: 66 | skipped_count += 1 67 | 68 | pbar.set_description( 69 | "Failed: {} Skipped: {}".format(error_count, skipped_count), refresh=False 70 | ) 71 | pbar.update(1) 72 | pbar.close() 73 | 74 | if error_count == 0: 75 | shutil.rmtree(cwd) 76 | -------------------------------------------------------------------------------- /emireduce.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | import os 4 | import sys 5 | import subprocess 6 | import shutil 7 | 8 | # python3 emireduce.py 9 | 10 | # TODO: pass sequence reduction 11 | opt_bin = sys.argv[1] 12 | ubi_path = sys.argv[2] 13 | llubi_bin = os.path.join(ubi_path, "llubi") 14 | if not os.path.exists(llubi_bin): 15 | print("llubi not found") 16 | sys.exit(1) 17 | emireduce_bin = os.path.join(ubi_path, "emireduce") 18 | if not os.path.exists(emireduce_bin): 19 | print("emireduce not found") 20 | sys.exit(1) 21 | src_ir = sys.argv[3] 22 | reduced_ir = sys.argv[4] 23 | reduced_tmp_ir = reduced_ir.removesuffix(".ll") + ".tmp.ll" 24 | reduced_opt_ir = reduced_ir.removesuffix(".ll") + ".opt.ll" 25 | max_retrial = 100 26 | 27 | def exec_ir(path): 28 | try: 29 | return subprocess.check_output([llubi_bin, path, "--max-steps", "100000000"], stderr=subprocess.DEVNULL).decode("utf-8") 30 | except Exception: 31 | return None 32 | 33 | def reduce_ir(path, output_path): 34 | try: 35 | out = subprocess.check_output([emireduce_bin, path, output_path]).decode("utf-8") 36 | if "No changes" in out: 37 | return None 38 | return out 39 | except Exception: 40 | print("Internal bug") 41 | exit(-1) 42 | 43 | def opt_ir(path, output_path): 44 | try: 45 | subprocess.check_output([opt_bin, "-S", "-O3", path, "-o", output_path]) 46 | return True 47 | except Exception: 48 | return False 49 | 50 | shutil.copyfile(src_ir, reduced_ir) 51 | ref_output = exec_ir(reduced_ir) 52 | orig_size = os.path.getsize(reduced_ir) 53 | if not opt_ir(reduced_ir, reduced_opt_ir): 54 | print("Failed to optimize") 55 | sys.exit(1) 56 | wrong_output = exec_ir(reduced_opt_ir) 57 | if ref_output == wrong_output: 58 | print("Test case is not interesting") 59 | sys.exit(0) 60 | 61 | def reduce_once(): 62 | ref_output = reduce_ir(reduced_ir, reduced_tmp_ir) 63 | if ref_output is None: 64 | return False 65 | if not opt_ir(reduced_tmp_ir, reduced_opt_ir): 66 | os.remove(reduced_tmp_ir) 67 | return False 68 | cur_output = exec_ir(reduced_opt_ir) 69 | if cur_output == ref_output: 70 | os.remove(reduced_tmp_ir) 71 | os.remove(reduced_opt_ir) 72 | return False 73 | shutil.move(reduced_tmp_ir, reduced_ir) 74 | os.remove(reduced_opt_ir) 75 | return True 76 | 77 | reduce_iter = 0 78 | reduce_fail_count = 0 79 | while True: 80 | reduce_iter += 1 81 | current_size = os.path.getsize(reduced_ir) 82 | print(f"Iteration {reduce_iter} {current_size} bytes ({current_size/orig_size*100:.2f}%) fail count {reduce_fail_count}") 83 | if reduce_once(): 84 | reduce_fail_count = 0 85 | else: 86 | reduce_fail_count += 1 87 | if reduce_fail_count >= max_retrial: 88 | break 89 | opt_ir(reduced_ir, reduced_opt_ir) 90 | 91 | print(f"Final size {os.path.getsize(reduced_ir)} bytes ({os.path.getsize(reduced_ir)/orig_size*100:.2f}%)") 92 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # llvm-ub-aware-interpreter (llubi) 2 | UB-aware interpreter for LLVM debugging 3 | 4 | ## Introduction 5 | 6 | This tool is developed to save my life when debugging LLVM. Unlike lli, this interpreter is UB-aware, which means it will check immediate undefined behaviors during execution and handle poison values properly. It is designed to be a debugging tool, so it is not optimized for performance. [alive-exec](https://github.com/AliveToolkit/alive2) should be a drop-in replacement for this tool. But it is slow and easy to get stuck in my experience. So this tool is designed to be more friendly to csmith and creduce. 7 | 8 | ## Motivation 9 | 10 | We have suffered from incorrect poison-generating/UB-implying annotations in LLVM for a long time. The most common mistake is that we forget to drop annotations after replacing one of its operands in place. In most cases, this kind of bugs will not be caught by end-to-end tests or real-world applications. But they will finally emerge when we do some aggressive optimizations with these incorrect annotations. With this interpreter, we can easily find out the incorrect annotations handling and fix them. 11 | 12 | Here is an incomplete list of this kind of bugs: 13 | + https://github.com/llvm/llvm-project/issues/115976 14 | + https://github.com/llvm/llvm-project/issues/115890 15 | + https://github.com/llvm/llvm-project/issues/114879 16 | + https://github.com/llvm/llvm-project/issues/113997 17 | + https://github.com/llvm/llvm-project/issues/112666 18 | + https://github.com/llvm/llvm-project/issues/112476 19 | + https://github.com/llvm/llvm-project/issues/112356 20 | + https://github.com/llvm/llvm-project/issues/112350 21 | + https://github.com/llvm/llvm-project/issues/112078 22 | + https://github.com/llvm/llvm-project/issues/112076 23 | + https://github.com/llvm/llvm-project/issues/112068 24 | + https://github.com/llvm/llvm-project/issues/111934 25 | + https://github.com/llvm/llvm-project/issues/99436 26 | + https://github.com/llvm/llvm-project/issues/91691 27 | + https://github.com/llvm/llvm-project/issues/91178 28 | + https://github.com/llvm/llvm-project/issues/91127 29 | + https://github.com/llvm/llvm-project/issues/90380 30 | + https://github.com/llvm/llvm-project/issues/87042 31 | + https://github.com/llvm/llvm-project/issues/85536 32 | + https://github.com/llvm/llvm-project/issues/78621 33 | 34 | ## Getting Started 35 | 36 | ``` 37 | git clone https://github.com/dtcxzyw/llvm-ub-aware-interpreter 38 | cd llvm-ub-aware-interpreter 39 | mkdir -p build && cd build 40 | cmake .. -GNinja -DCMAKE_BUILD_TYPE=Release -DLLVM_DIR=/path/to/llvm/lib/cmake/llvm 41 | cmake --build . -j 42 | ./llubi test.ll [--verbose] 43 | ``` 44 | 45 | ## Automatic UB-Free Test Case Reduction for Middle-End Miscompilation Bugs 46 | 47 | test.sh: 48 | ``` 49 | #!/usr/bin/bash 50 | 51 | MAX_STEPS=1000000 52 | a=$( --max-steps $MAX_STEPS --reduce-mode $1) 53 | if [ $? -ne 0 ]; then 54 | exit 1 55 | fi 56 | $1 -o $1.tmp 57 | if [ $? -ne 0 ]; then 58 | exit 1 59 | fi 60 | b=$( --max-steps $MAX_STEPS --reduce-mode $1.tmp) 61 | if [ $? -ne 0 ]; then 62 | rm $1.tmp 63 | exit 0 64 | fi 65 | if [[ $a == $b ]]; then 66 | rm $1.tmp 67 | exit 1 68 | fi 69 | rm $1.tmp 70 | exit 0 71 | ``` 72 | 73 | Usage: 74 | ``` 75 | clang -O3 -Xclang -disable-llvm-passes -emit-llvm -S test.c -o test.ll 76 | llvm-reduce --test=test.sh --ir-passes="function(sroa,instcombine,gvn,simplifycfg,infer-address-spaces),inline" test.ll 77 | ``` 78 | 79 | Please refer to [this example](https://github.com/llvm/llvm-project/issues/131465#issuecomment-2727536818) if you find it hard to get a valid reproducer. 80 | BTW, an automatic reproducer reduction pipeline will be available soon :) 81 | 82 | ## Fuzzing with Csmith 83 | ``` 84 | python3 csmith.py [emi] 85 | ``` 86 | If `emi` is set, it will enable the EMI-based mutation. For more details, please refer to [Compiler validation via equivalence modulo inputs, PLDI'21](https://dl.acm.org/doi/10.1145/2594291.2594334). 87 | 88 | ## Fuzzing with Rustlantis 89 | [Rustlantis](https://github.com/dtcxzyw/rustlantis) has been adapted to support llubi. 90 | 91 | ``` 92 | git clone https://github.com/dtcxzyw/rustlantis.git 93 | cp rustlantis/config.toml.example ./config.toml 94 | echo "llubi_path=$(pwd)/build/llubi" >>config.toml 95 | python3 rustlantis.py ./rustlantis 96 | ``` 97 | 98 | ## Limitations 99 | We did some refinements on the LLVM LangRef to make the implementation practical and efficient: 100 | 101 | + It only checks **guardable** UBs. That is, they are checked at the point of instruction execution. Some non-guardable UBs, like mustprogress violation (i.e., infinite loop), are not checked. 102 | + `nsz` attribute is not supported. 103 | + Undef values are not supported as we will eventually remove undef from LLVM in the future. In llubi, they are treated as zero values. 104 | + FFI is not supported. Currently it only supports ```printf("%d", x)``` for csmith. Some Rust standard library functions are patched to support rustlantis. 105 | + Addresses of allocations are unique. That is, we cannot model the behavior of stack coloring in llubi. 106 | + Pointer aliasing has not been supported yet. 107 | + Pointer provenance and capture tracking support is limited. We do not track the capabilities of pointers if it is stored into memory or converted to an integer. 108 | + We do not maintain the precise poison semantics in memory. 109 | + We do not check ```externally observable sideeffects``` strictly as required by ```memory(read)/readonly```. The current implementation just works for these two fuzzers. 110 | + Volatile memory accesses are partially supported. We only record the total number of bytes that are loaded/stored via volatile memory ops. 111 | 112 | ## License 113 | 114 | This repository is licensed under the Apache License 2.0. See [LICENSE](LICENSE) for details. 115 | 116 | ## Citation 117 | 118 | Please cite this work with the following BibTex entry: 119 | 120 | ``` 121 | @misc{llubi, 122 | title = {LLVM UB-Aware Interpreter}, 123 | url = {https://github.com/dtcxzyw/llvm-ub-aware-interpreter}, 124 | author = {Yingwei Zheng}, 125 | year = {2024}, 126 | } 127 | ``` 128 | -------------------------------------------------------------------------------- /llubi.cpp: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0 2 | // Copyright (c) 2024 Yingwei Zheng 3 | // This file is licensed under the Apache-2.0 License. 4 | // See the LICENSE file for more information. 5 | 6 | #include "ubi.h" 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | 15 | using namespace llvm; 16 | static cl::OptionCategory Category("LLUBI Options"); 17 | static cl::opt InputFile(cl::Positional, cl::desc(""), 18 | cl::Required, 19 | cl::value_desc("path to input IR"), 20 | cl::cat(Category)); 21 | static cl::opt VScaleValue("vscale", 22 | cl::value_desc("value for llvm.vscale"), 23 | cl::init(4U), cl::cat(Category)); 24 | static cl::opt 25 | MaxSteps("max-steps", cl::value_desc("Max steps to run"), 26 | cl::init(std::numeric_limits::max()), cl::cat(Category)); 27 | static cl::opt IgnoreParamAttrsOnIntrinsic( 28 | "ignore-param-attrs-intrinsic", 29 | cl::desc("Ignore parameter attributes of intrinsic calls"), cl::init(false), 30 | cl::cat(Category)); 31 | static cl::opt ReduceMode("reduce-mode", 32 | cl::desc("Reduce mode (allow invalid IR)"), 33 | cl::init(false), cl::cat(Category)); 34 | static cl::opt Verbose("verbose", cl::desc("Print step-by-step log"), 35 | cl::init(false), cl::cat(Category)); 36 | static cl::opt EMIMutate("emi", 37 | cl::desc("Enable EMI-based mutation"), 38 | cl::value_desc("Path to output IR file"), 39 | cl::cat(Category)); 40 | static cl::opt DumpEMI("dump-emi", 41 | cl::desc("Dump EMI-based mutation scheme"), 42 | cl::init(false), cl::cat(Category)); 43 | static cl::opt 44 | DumpStackTrace("dump-stack-trace", 45 | cl::desc("Dump stack trace when immediate UB occurs"), 46 | cl::init(true), cl::cat(Category)); 47 | static cl::opt 48 | TrackVolatileMem("track-volatile-mem", 49 | cl::desc("Track volatile memory accesses"), 50 | cl::init(false), cl::cat(Category)); 51 | static cl::opt 52 | VerifyValueTracking("verify-value-tracking", 53 | cl::desc("Verify analysis results of value tracking"), 54 | cl::init(false), cl::cat(Category)); 55 | static cl::opt VeriySCEV("verify-scev-res", 56 | cl::desc("Verify analysis results of SCEV"), 57 | cl::init(false), cl::cat(Category)); 58 | static cl::opt 59 | VerifyLVI("verify-lvi", 60 | cl::desc("Verify analysis results of LazyValueInfo"), 61 | cl::init(false), cl::cat(Category)); 62 | static cl::opt 63 | StorePoisonIsNoop("store-poison-is-noop", 64 | cl::desc("Treat store poison as a no-op"), 65 | cl::init(false), cl::cat(Category)); 66 | static cl::opt 67 | StorePoisonIsImmUB("store-poison-is-ub", 68 | cl::desc("Treat store poison as an immediate UB"), 69 | cl::init(true), cl::cat(Category)); 70 | static cl::opt FreezeBytes("freeze-bytes", 71 | cl::desc("Freeze bytes in memory"), 72 | cl::init(false), cl::cat(Category)); 73 | static cl::opt RustMode("rust", cl::desc("Run rust programs"), 74 | cl::init(false), cl::cat(Category)); 75 | static cl::opt 76 | IgnoreExplicitLifetimeMarker("ignore-explicit-lifetime-marker", 77 | cl::desc("Ignore explicit lifetime markers"), 78 | cl::init(false), cl::cat(Category)); 79 | static cl::opt EnforceStackOrderLifetimeMarker( 80 | "enforce-stack-order-lifetime-marker", 81 | cl::desc("Ensure lifetime.start/end execute in a stack order"), 82 | cl::init(false), cl::cat(Category)); 83 | static cl::opt FillUninitializedMemWithPoison( 84 | "fill-uninitialized-mem-with-poison", 85 | cl::desc("Fill uninitialized memory with poison to sync with alive2"), 86 | cl::init(false), cl::cat(Category)); 87 | static cl::opt FuseFMulAdd("fuse-fmuladd", 88 | cl::desc("Treat fmuladd as fma"), 89 | cl::init(false), cl::cat(Category)); 90 | 91 | int main(int argc, char **argv) { 92 | InitLLVM Init{argc, argv}; 93 | cl::HideUnrelatedOptions(Category); 94 | cl::ParseCommandLineOptions(argc, argv, 95 | "llubi -- LLVM ub-aware interpreter\n"); 96 | 97 | LLVMContext Ctx; 98 | SMDiagnostic Err; 99 | std::unique_ptr M = parseIRFile(InputFile, Err, Ctx); 100 | if (!M) { 101 | Err.print(argv[0], errs()); 102 | return EXIT_FAILURE; 103 | } 104 | 105 | InterpreterOption Option; 106 | 107 | Option.ReduceMode = ReduceMode; 108 | Option.VScale = VScaleValue; 109 | Option.MaxSteps = MaxSteps; 110 | Option.Verbose = Verbose; 111 | Option.EnableEMITracking = !EMIMutate.empty(); 112 | Option.EnableEMIDebugging = DumpEMI; 113 | Option.TrackVolatileMem = TrackVolatileMem; 114 | Option.VerifyValueTracking = VerifyValueTracking; 115 | Option.VerifySCEV = VeriySCEV; 116 | Option.VerifyLazyValueInfo = VerifyLVI; 117 | Option.IgnoreParamAttrsOnIntrinsic = IgnoreParamAttrsOnIntrinsic; 118 | Option.DumpStackTrace = DumpStackTrace; 119 | Option.StorePoisonIsNoop = StorePoisonIsNoop; 120 | Option.RustMode = RustMode; 121 | Option.IgnoreExplicitLifetimeMarker = IgnoreExplicitLifetimeMarker; 122 | Option.EnforceStackOrderLifetimeMarker = EnforceStackOrderLifetimeMarker; 123 | Option.FillUninitializedMemWithPoison = FillUninitializedMemWithPoison; 124 | Option.FuseFMulAdd = FuseFMulAdd; 125 | Option.FreezeBytes = FreezeBytes; 126 | Option.StorePoisonIsImmUB = StorePoisonIsImmUB; 127 | 128 | UBAwareInterpreter Executor(*M, Option); 129 | int32_t Ret = Executor.runMain(); 130 | if (!EMIMutate.empty()) { 131 | Executor.mutate(); 132 | std::error_code EC; 133 | raw_fd_ostream Out{EMIMutate.getValue(), EC, sys::fs::OF_Text}; 134 | if (EC) { 135 | errs() << "Error: " << EC.message() << '\n'; 136 | return EXIT_FAILURE; 137 | } 138 | Out << *M; 139 | Out.flush(); 140 | } 141 | return Ret; 142 | } 143 | -------------------------------------------------------------------------------- /emireduce.cpp: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0 2 | // Copyright (c) 2024 Yingwei Zheng 3 | // This file is licensed under the Apache-2.0 License. 4 | // See the LICENSE file for more information. 5 | 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include "ubi.h" 13 | #include 14 | #include 15 | #include 16 | #include 17 | #include 18 | #include 19 | 20 | using namespace llvm; 21 | using namespace PatternMatch; 22 | static cl::OptionCategory Category("EMIReduce Options"); 23 | static cl::opt InputFile(cl::Positional, cl::desc(""), 24 | cl::Required, 25 | cl::value_desc("path to input IR"), 26 | cl::cat(Category)); 27 | static cl::opt VScaleValue("vscale", 28 | cl::value_desc("value for llvm.vscale"), 29 | cl::init(4U), cl::cat(Category)); 30 | static cl::opt OutputFile(cl::Positional, cl::desc(""), 31 | cl::Required, 32 | cl::value_desc("path to output IR"), 33 | cl::cat(Category)); 34 | 35 | static Constant *constantFoldInst(Instruction *I) { 36 | if (auto *BO = dyn_cast(I)) { 37 | if (auto *LHS = dyn_cast(BO->getOperand(0))) 38 | if (auto *RHS = dyn_cast(BO->getOperand(1))) 39 | return ConstantFoldBinaryInstruction(BO->getOpcode(), LHS, RHS); 40 | } 41 | if (auto *UI = dyn_cast(I)) { 42 | if (auto *V = dyn_cast(UI->getOperand(0))) 43 | return ConstantFoldUnaryInstruction(UI->getOpcode(), V); 44 | } 45 | if (auto *CI = dyn_cast(I)) { 46 | if (auto *V = dyn_cast(CI->getOperand(0))) 47 | return ConstantFoldCastInstruction(CI->getOpcode(), V, CI->getType()); 48 | } 49 | if (auto *SI = dyn_cast(I)) { 50 | if (auto *Cond = dyn_cast(SI->getCondition())) 51 | if (auto *V1 = dyn_cast(SI->getTrueValue())) 52 | if (auto *V2 = dyn_cast(SI->getFalseValue())) 53 | return ConstantFoldSelectInstruction(Cond, V1, V2); 54 | } 55 | if (auto *EI = dyn_cast(I)) { 56 | if (auto *Val = dyn_cast(EI->getVectorOperand())) 57 | if (auto *Idx = dyn_cast(EI->getIndexOperand())) 58 | return ConstantFoldExtractElementInstruction(Val, Idx); 59 | } 60 | if (auto *II = dyn_cast(I)) { 61 | if (auto *Val = dyn_cast(II->getOperand(0))) 62 | if (auto *Elt = dyn_cast(II->getOperand(1))) 63 | if (auto *Idx = dyn_cast(II->getOperand(2))) 64 | return ConstantFoldInsertElementInstruction(Val, Elt, Idx); 65 | } 66 | if (auto *SVI = dyn_cast(I)) { 67 | if (auto *V1 = dyn_cast(SVI->getOperand(0))) 68 | if (auto *V2 = dyn_cast(SVI->getOperand(1))) 69 | return ConstantFoldShuffleVectorInstruction(V1, V2, 70 | SVI->getShuffleMask()); 71 | } 72 | if (auto *EVI = dyn_cast(I)) { 73 | if (auto *Agg = dyn_cast(EVI->getAggregateOperand())) 74 | return ConstantFoldExtractValueInstruction(Agg, EVI->getIndices()); 75 | } 76 | if (auto *IVI = dyn_cast(I)) { 77 | if (auto *Agg = dyn_cast(IVI->getAggregateOperand())) 78 | if (auto *Val = dyn_cast(IVI->getInsertedValueOperand())) 79 | return ConstantFoldInsertValueInstruction(Agg, Val, IVI->getIndices()); 80 | } 81 | if (auto *CI = dyn_cast(I)) { 82 | if (auto *C1 = dyn_cast(CI->getOperand(0))) 83 | if (auto *C2 = dyn_cast(CI->getOperand(1))) 84 | return ConstantFoldCompareInstruction(CI->getPredicate(), C1, C2); 85 | } 86 | 87 | return nullptr; 88 | } 89 | 90 | static bool simplifyFunction(Function &F) { 91 | if (F.isDeclaration()) 92 | return false; 93 | bool Changed = false; 94 | for (auto &BB : F) { 95 | for (auto &I : make_early_inc_range(BB)) { 96 | if (isInstructionTriviallyDead(&I)) { 97 | I.eraseFromParent(); 98 | Changed = true; 99 | continue; 100 | } 101 | if (auto *V = constantFoldInst(&I)) { 102 | I.replaceAllUsesWith(V); 103 | I.eraseFromParent(); 104 | Changed = true; 105 | continue; 106 | } 107 | } 108 | 109 | Changed |= ConstantFoldTerminator(&BB, /*DeleteDeadConditions=*/true); 110 | } 111 | Changed |= removeUnreachableBlocks(F); 112 | return Changed; 113 | } 114 | static bool simplifyModule(Module &M) { 115 | bool Changed = false; 116 | for (auto &F : make_early_inc_range(M)) { 117 | Changed |= simplifyFunction(F); 118 | if (F.getName() != "main" && F.user_empty()) { 119 | F.eraseFromParent(); 120 | Changed = true; 121 | } 122 | } 123 | for (auto &GV : make_early_inc_range(M.globals())) { 124 | if (GV.user_empty()) { 125 | GV.eraseFromParent(); 126 | Changed = true; 127 | } 128 | } 129 | 130 | if (verifyModule(M, &errs())) { 131 | errs() << "Error: verification failed\n"; 132 | std::abort(); 133 | } 134 | return Changed; 135 | } 136 | 137 | int main(int argc, char **argv) { 138 | InitLLVM Init{argc, argv}; 139 | cl::HideUnrelatedOptions(Category); 140 | cl::ParseCommandLineOptions( 141 | argc, argv, 142 | "emireduce -- EMI-based semantic-preserving LLVM IR reducer\n"); 143 | 144 | LLVMContext Ctx; 145 | SMDiagnostic Err; 146 | std::unique_ptr M = parseIRFile(InputFile, Err, Ctx); 147 | if (!M) { 148 | Err.print(argv[0], errs()); 149 | return EXIT_FAILURE; 150 | } 151 | 152 | InterpreterOption Option; 153 | Option.VScale = VScaleValue; 154 | Option.EnableEMITracking = true; 155 | Option.EnablePGFTracking = false; 156 | Option.EMIProb = 0.1; 157 | Option.EMIUseProb = 1.01; 158 | UBAwareInterpreter Executor(*M, Option); 159 | int32_t Ret = Executor.runMain(); 160 | if (!Executor.simplify()) { 161 | outs() << "No changes\n"; 162 | return EXIT_SUCCESS; 163 | } 164 | simplifyModule(*M); 165 | std::error_code EC; 166 | raw_fd_ostream Out{OutputFile.getValue(), EC, sys::fs::OF_Text}; 167 | if (EC) { 168 | errs() << "Error: " << EC.message() << '\n'; 169 | return EXIT_FAILURE; 170 | } 171 | Out << *M; 172 | Out.flush(); 173 | return Ret; 174 | } 175 | -------------------------------------------------------------------------------- /csmith.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | from multiprocessing import Pool 4 | from tqdm import tqdm 5 | import os 6 | import sys 7 | import subprocess 8 | import shutil 9 | import tqdm 10 | import datetime 11 | import random 12 | 13 | # python3 ../csmith.py /usr ../../csmith/install/ ./llubi 1 14 | 15 | llvm_dir = sys.argv[1] 16 | csmith_dir = sys.argv[2] 17 | llubi_bin = sys.argv[3] 18 | test_count = int(sys.argv[4]) 19 | emi = len(sys.argv) >= 6 and sys.argv[5] == "emi" 20 | inconsistent = len(sys.argv) >= 6 and sys.argv[5] == "inconsistency" 21 | stepbystep = len(sys.argv) >= 6 and sys.argv[5] == "stepbystep" 22 | if emi: 23 | print("EMI-based mutation is enabled") 24 | if inconsistent: 25 | print("Inconsistency check is enabled") 26 | if stepbystep: 27 | print("Step-by-step check is enabled") 28 | csmith_command = ( 29 | csmith_dir 30 | + "/bin/csmith --max-funcs 3 --max-block-depth 5 --quiet --builtins --no-packed-struct --no-unions --no-bitfields --output " 31 | ) 32 | compile_command = ( 33 | llvm_dir + "/bin/clang -lm -DNDEBUG -g0 -w -I" + csmith_dir + "/include " 34 | ) 35 | comp_timeout = 10.0 36 | exec_timeout = 1.0 37 | llubi_workarounds = [ 38 | # https://github.com/llvm/llvm-project/issues/115890 39 | "--ignore-param-attrs-intrinsic", 40 | "--non-global-value-max-name-size=4096", 41 | ] 42 | if not inconsistent: 43 | # llubi_workarounds.append('--track-volatile-mem') 44 | pass 45 | 46 | cwd = "csmith" + datetime.datetime.now().strftime("%Y-%m-%d@%H:%M") 47 | os.makedirs(cwd) 48 | 49 | no_report_env = { 50 | "LLVM_DISABLE_CRASH_REPORT": "1", 51 | "LLVM_DISABLE_SYMBOLIZATION": "1", 52 | } 53 | 54 | 55 | def check_step_by_step(file_c, basename): 56 | file_o0_output = basename + ".O0.ll" 57 | try: 58 | comp_command = ( 59 | compile_command 60 | + " -o " 61 | + file_o0_output 62 | + " " 63 | + file_c 64 | + " -O3 -Xclang -disable-llvm-passes -emit-llvm -S" 65 | ) 66 | subprocess.check_call( 67 | comp_command.split(" "), 68 | timeout=comp_timeout, 69 | stderr=subprocess.DEVNULL, 70 | ) 71 | except Exception: 72 | os.remove(file_c) 73 | return None 74 | 75 | try: 76 | ref_out = subprocess.check_output( 77 | [llubi_bin, file_o0_output] + llubi_workarounds, 78 | timeout=exec_timeout * 5, 79 | env=no_report_env, 80 | ) 81 | except subprocess.TimeoutExpired: 82 | # Ignore timeout 83 | os.remove(file_c) 84 | os.remove(file_o0_output) 85 | return True 86 | except Exception: 87 | return False 88 | 89 | idx = 1 90 | while True: 91 | file_i_output = basename + "." + str(idx) + ".ll" 92 | try: 93 | comp_command = ( 94 | compile_command 95 | + " -o " 96 | + file_i_output 97 | + " " 98 | + file_c 99 | + " -O3 -emit-llvm -S" 100 | + " -mllvm -opt-bisect-limit=" 101 | + str(idx) 102 | ) 103 | ret = subprocess.run( 104 | comp_command.split(" "), 105 | timeout=comp_timeout, 106 | check=True, 107 | capture_output=True, 108 | ) 109 | if f"({idx})" not in ret.stderr.decode(): 110 | os.remove(file_c) 111 | os.remove(file_i_output) 112 | os.remove(file_o0_output) 113 | return True 114 | except Exception: 115 | os.remove(file_c) 116 | os.remove(file_o0_output) 117 | return None 118 | 119 | try: 120 | out = subprocess.check_output( 121 | [llubi_bin, file_i_output] + llubi_workarounds, 122 | timeout=exec_timeout * 5, 123 | env=no_report_env, 124 | ) 125 | except subprocess.TimeoutExpired: 126 | # Ignore timeout 127 | os.remove(file_c) 128 | os.remove(file_i_output) 129 | return True 130 | except Exception: 131 | return False 132 | 133 | if out != ref_out: 134 | return False 135 | os.remove(file_i_output) 136 | idx += 1 137 | 138 | 139 | def csmith_test(i): 140 | basename = cwd + "/test" + str(i) 141 | file_c = basename + ".c" 142 | try: 143 | subprocess.check_call((csmith_command + file_c).split(" ")) 144 | except subprocess.SubprocessError: 145 | return None 146 | 147 | if stepbystep: 148 | return check_step_by_step(file_c, basename) 149 | 150 | file_out = basename + ".ll" 151 | try: 152 | comp_command = compile_command + " -o " + file_out + " " + file_c 153 | subprocess.check_call(comp_command.split(" "), timeout=comp_timeout) 154 | except subprocess.TimeoutExpired: 155 | os.remove(file_c) 156 | if os.path.exists(file_out): 157 | os.remove(file_out) 158 | return None 159 | except subprocess.CalledProcessError: 160 | return False 161 | 162 | try: 163 | subprocess.check_call( 164 | [file_out], 165 | timeout=exec_timeout, 166 | stderr=subprocess.DEVNULL, 167 | stdout=subprocess.DEVNULL, 168 | ) 169 | subprocess.check_call( 170 | ( 171 | comp_command 172 | + " -O3 -emit-llvm -S" 173 | + ( 174 | " -mllvm -opt-bisect-limit=" + str(random.randint(0, 1000)) 175 | if emi 176 | else "" 177 | ) 178 | ).split(" "), 179 | timeout=comp_timeout, 180 | stderr=subprocess.DEVNULL, 181 | ) 182 | except Exception: 183 | if os.path.exists(file_out): 184 | os.remove(file_out) 185 | os.remove(file_c) 186 | return None 187 | 188 | if emi: 189 | file_emi_out = basename + ".emi.ll" 190 | try: 191 | ref_out = subprocess.check_output( 192 | [llubi_bin, file_out, "--emi", file_emi_out] + llubi_workarounds, 193 | timeout=exec_timeout, 194 | env=no_report_env, 195 | ) 196 | except subprocess.TimeoutExpired: 197 | # Ignore timeout 198 | os.remove(file_c) 199 | os.remove(file_out) 200 | if os.path.exists(file_emi_out): 201 | os.remove(file_emi_out) 202 | return None 203 | except Exception: 204 | return False 205 | 206 | file_emi_opt_out = basename + ".emiopt.ll" 207 | try: 208 | subprocess.check_call( 209 | [ 210 | llvm_dir + "/bin/opt", 211 | "-O3", 212 | file_emi_out, 213 | "-S", 214 | "-o", 215 | file_emi_opt_out, 216 | ], 217 | timeout=comp_timeout, 218 | stderr=subprocess.DEVNULL, 219 | ) 220 | except subprocess.TimeoutExpired: 221 | # Ignore timeout 222 | os.remove(file_c) 223 | os.remove(file_out) 224 | os.remove(file_emi_out) 225 | return None 226 | except Exception: 227 | return False 228 | 229 | try: 230 | out = subprocess.check_output( 231 | [llubi_bin, file_emi_opt_out] + llubi_workarounds, 232 | timeout=exec_timeout * 5, 233 | env=no_report_env, 234 | ) 235 | except subprocess.TimeoutExpired: 236 | # Ignore timeout 237 | os.remove(file_c) 238 | os.remove(file_out) 239 | os.remove(file_emi_out) 240 | os.remove(file_emi_opt_out) 241 | return True 242 | except Exception: 243 | return False 244 | 245 | if out == ref_out: 246 | os.remove(file_c) 247 | os.remove(file_out) 248 | os.remove(file_emi_out) 249 | os.remove(file_emi_opt_out) 250 | return True 251 | 252 | else: 253 | if inconsistent: 254 | try: 255 | ref_out = subprocess.check_output( 256 | [llvm_dir + "/bin/lli", file_out], 257 | timeout=exec_timeout, 258 | stderr=subprocess.DEVNULL, 259 | ) 260 | except Exception: 261 | os.remove(file_c) 262 | os.remove(file_out) 263 | return None 264 | else: 265 | file_o0_output = basename + ".O0.ll" 266 | try: 267 | comp_command = ( 268 | compile_command 269 | + " -o " 270 | + file_o0_output 271 | + " " 272 | + file_c 273 | + " -O3 -Xclang -disable-llvm-passes -emit-llvm -S" 274 | ) 275 | subprocess.check_call( 276 | comp_command.split(" "), 277 | timeout=comp_timeout, 278 | stderr=subprocess.DEVNULL, 279 | ) 280 | except Exception: 281 | os.remove(file_out) 282 | os.remove(file_c) 283 | return None 284 | 285 | try: 286 | ref_out = subprocess.check_output( 287 | [llubi_bin, file_o0_output] + llubi_workarounds, 288 | timeout=exec_timeout * 5, 289 | env=no_report_env, 290 | ) 291 | except subprocess.TimeoutExpired: 292 | # Ignore timeout 293 | os.remove(file_c) 294 | os.remove(file_out) 295 | os.remove(file_o0_output) 296 | return None 297 | except Exception: 298 | return False 299 | 300 | try: 301 | out = subprocess.check_output( 302 | [llubi_bin, file_out] 303 | + llubi_workarounds 304 | + ["--verify-value-tracking", "--verify-scev-res", "--verify-lvi"], 305 | timeout=exec_timeout * 5, 306 | env=no_report_env, 307 | ) 308 | except subprocess.TimeoutExpired: 309 | # Ignore timeout 310 | os.remove(file_c) 311 | os.remove(file_out) 312 | if not inconsistent: 313 | os.remove(file_o0_output) 314 | return None 315 | except Exception: 316 | return False 317 | 318 | if out == ref_out: 319 | os.remove(file_c) 320 | os.remove(file_out) 321 | if not inconsistent: 322 | os.remove(file_o0_output) 323 | return True 324 | return False 325 | 326 | 327 | L = list(range(test_count)) 328 | pbar = tqdm.tqdm(L) 329 | error_count = 0 330 | skipped_count = 0 331 | pool = Pool(os.cpu_count()) 332 | 333 | for res in pool.imap_unordered(csmith_test, L): 334 | if res is not None: 335 | error_count += 0 if res else 1 336 | else: 337 | skipped_count += 1 338 | 339 | pbar.set_description( 340 | "Failed: {} Skipped: {}".format(error_count, skipped_count), refresh=False 341 | ) 342 | pbar.update(1) 343 | pbar.close() 344 | 345 | if error_count == 0: 346 | shutil.rmtree(cwd) 347 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /ubi.h: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0 2 | // Copyright (c) 2024 Yingwei Zheng 3 | // This file is licensed under the Apache-2.0 License. 4 | // See the LICENSE file for more information. 5 | 6 | #pragma once 7 | 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include 15 | #include 16 | #include 17 | #include 18 | #include 19 | #include 20 | #include 21 | #include 22 | #include 23 | #include 24 | #include 25 | #include 26 | #include 27 | #include 28 | #include 29 | #include 30 | #include 31 | #include 32 | #include 33 | #include 34 | #include 35 | #include 36 | #include 37 | #include 38 | #include 39 | #include 40 | #include 41 | #include 42 | #include 43 | #include 44 | #include 45 | #include 46 | #include 47 | #include 48 | #include 49 | #include 50 | #include 51 | #include 52 | #include 53 | #include 54 | #include 55 | #include 56 | #include 57 | #include 58 | #include 59 | #include 60 | #include 61 | #include 62 | #include 63 | #include 64 | #include 65 | #include 66 | #include 67 | #include 68 | #include 69 | #include 70 | #include 71 | #include 72 | #include 73 | #include 74 | #include 75 | #include 76 | #include 77 | #include 78 | #include 79 | #include 80 | 81 | using namespace llvm; 82 | 83 | class MemoryManager; 84 | struct Frame; 85 | 86 | struct MemByteMetadata { 87 | bool IsPoison : 1 = false; 88 | // Pointer permission info 89 | bool Readable : 1 = false; 90 | bool Writable : 1 = false; 91 | bool Comparable : 1 = false; 92 | bool ComparableWithNull : 1 = false; 93 | }; 94 | 95 | static_assert(sizeof(MemByteMetadata) == 1, "MemByteMetadata should be 1 byte"); 96 | 97 | class MemObject final : public std::enable_shared_from_this { 98 | MemoryManager &Manager; 99 | std::string Name; 100 | bool IsLocal; 101 | Frame *StackObjectInfo; 102 | APInt Address; 103 | SmallVector Data; 104 | SmallVector Metadata; 105 | bool IsAlive; 106 | bool IsConstant; 107 | 108 | public: 109 | explicit MemObject(MemoryManager &Manager, std::string Name, bool IsLocal, 110 | APInt PtrAddress, size_t Size) 111 | : Manager(Manager), Name(std::move(Name)), IsLocal(IsLocal), 112 | StackObjectInfo(nullptr), Address(std::move(PtrAddress)), Data(Size), 113 | Metadata(Size), IsAlive(true), IsConstant(false) {} 114 | ~MemObject(); 115 | void setStackObjectInfo(Frame *FrameCtx) { StackObjectInfo = FrameCtx; } 116 | void markConstant() { IsConstant = true; } 117 | void setLiveness(bool Alive) { IsAlive = Alive; } 118 | void markPoison(size_t Offset, size_t Size, bool IsPoison); 119 | MemByteMetadata &getMetadata(size_t Offset) { return Metadata[Offset]; } 120 | const MemByteMetadata &getMetadata(size_t Offset) const { 121 | return Metadata[Offset]; 122 | } 123 | void verifyMemAccess(size_t Offset, size_t AccessSize, size_t Alignment, 124 | bool IsStore); 125 | void store(size_t Offset, const APInt &C); 126 | std::optional load(size_t Offset, size_t Bits, bool FreezeBytes) const; 127 | APInt address() const { return Address; } 128 | size_t size() const { return Data.size(); } 129 | char *rawPointer() { return reinterpret_cast(Data.data()); } 130 | void dumpName(raw_ostream &Out) const; 131 | void dump(raw_ostream &Out) const; 132 | bool isGlobal() const noexcept { return !IsLocal; } 133 | bool isStackObject(Frame *Ctx) const noexcept { 134 | return StackObjectInfo == Ctx; 135 | } 136 | bool isAlive() const noexcept { return IsAlive; } 137 | bool isConstant() const noexcept { return IsConstant; } 138 | }; 139 | 140 | inline raw_ostream &operator<<(raw_ostream &Out, const MemObject &MO) { 141 | MO.dump(Out); 142 | return Out; 143 | } 144 | 145 | struct ContextSensitivePointerInfo { 146 | std::shared_ptr Parent; 147 | Frame *FrameCtx; 148 | bool Readable : 1; 149 | bool Writable : 1; 150 | bool Comparable : 1; 151 | bool ComparableWithNull : 1; 152 | uint32_t Loc : 2; 153 | CaptureInfo CI; 154 | 155 | static ContextSensitivePointerInfo getDefault(Frame *FrameCtx); 156 | void push(Frame *Ctx); 157 | void pushReadWrite(Frame *Ctx, bool Readable, bool Writable) { 158 | push(Ctx); 159 | this->Readable = Readable; 160 | this->Writable = Writable; 161 | } 162 | void pushLoc(Frame *Ctx, IRMemLocation Loc) { 163 | push(Ctx); 164 | this->Loc = static_cast(Loc); 165 | } 166 | IRMemLocation getLoc() const { return static_cast(Loc); } 167 | void pushCaptureInfo(Frame *Ctx, CaptureInfo CI) { 168 | push(Ctx); 169 | this->CI &= CI; 170 | } 171 | void pushComparable(Frame *Ctx, bool Comparable) { 172 | push(Ctx); 173 | this->Comparable = Comparable; 174 | } 175 | void pushComparableWithNull(Frame *Ctx, bool ComparableWithNull) { 176 | push(Ctx); 177 | this->ComparableWithNull = ComparableWithNull; 178 | } 179 | void pop(Frame *Ctx); 180 | }; 181 | 182 | struct Pointer final { 183 | std::weak_ptr Obj; 184 | APInt Address; 185 | uint32_t Offset; 186 | uint32_t Bound; 187 | ContextSensitivePointerInfo Info; 188 | 189 | explicit Pointer(const std::shared_ptr &Obj, uint32_t Offset, 190 | ContextSensitivePointerInfo Info) 191 | : Obj(Obj), Address(Obj->address() + Offset), Offset(Offset), 192 | Bound(Obj->size()), Info(std::move(Info)) {} 193 | explicit Pointer(const std::weak_ptr &Obj, uint32_t NewOffset, 194 | APInt NewAddress, uint32_t NewBound, 195 | ContextSensitivePointerInfo Info) 196 | : Obj(Obj), Address(std::move(NewAddress)), Offset(NewOffset), 197 | Bound(NewBound), Info(std::move(Info)) {} 198 | }; 199 | 200 | using SingleValue = std::variant; 201 | inline bool isPoison(const SingleValue &SV) { 202 | return std::holds_alternative(SV); 203 | } 204 | inline bool isPoison(const APFloat &AFP, FastMathFlags FMF) { 205 | if (FMF.noNaNs() && AFP.isNaN()) 206 | return true; 207 | if (FMF.noInfs() && AFP.isInfinity()) 208 | return true; 209 | return false; 210 | } 211 | inline SingleValue boolean(bool Val) { return SingleValue{APInt(1, Val)}; } 212 | inline SingleValue poison() { return std::monostate{}; } 213 | bool refines(const SingleValue &LHS, const SingleValue &RHS); 214 | 215 | class UBAwareInterpreter; 216 | 217 | class MemoryManager final { 218 | UBAwareInterpreter &Interpreter; 219 | uint32_t PtrBitWidth; 220 | size_t AllocatedMem = 0; 221 | static constexpr size_t Padding = 1024U; 222 | std::map AddressMap; 223 | 224 | friend class MemObject; 225 | void erase(const size_t Address) { AddressMap.erase(Address); } 226 | 227 | public: 228 | explicit MemoryManager(UBAwareInterpreter &Interpreter, const DataLayout &DL, 229 | PointerType *Ty); 230 | std::shared_ptr create(std::string Name, bool IsLocal, size_t Size, 231 | size_t Alignment); 232 | SingleValue lookupPointer(const APInt &Addr) const; 233 | }; 234 | struct AnyValue final { 235 | std::variant> Val; 236 | 237 | AnyValue(SingleValue SV) : Val(std::move(SV)) {} 238 | AnyValue(std::vector MV) : Val(std::move(MV)) {} 239 | AnyValue() = default; 240 | 241 | bool isSingleValue() const { 242 | return std::holds_alternative(Val); 243 | } 244 | const SingleValue &getSingleValue() const { 245 | assert(isSingleValue()); 246 | return std::get(Val); 247 | } 248 | SingleValue &getSingleValue() { 249 | assert(isSingleValue()); 250 | return std::get(Val); 251 | } 252 | const std::vector &getValueArray() const { 253 | assert(std::holds_alternative>(Val)); 254 | return std::get>(Val); 255 | } 256 | std::vector &getValueArray() { 257 | assert(std::holds_alternative>(Val)); 258 | return std::get>(Val); 259 | } 260 | const SingleValue &getSingleValueAt(uint32_t Idx) const { 261 | return getValueArray().at(Idx).getSingleValue(); 262 | } 263 | SingleValue &getSingleValueAt(uint32_t Idx) { 264 | return getValueArray().at(Idx).getSingleValue(); 265 | } 266 | bool refines(const AnyValue &RHS) const; 267 | }; 268 | raw_ostream &operator<<(raw_ostream &Out, const AnyValue &Val); 269 | 270 | struct FunctionAnalysisCache final { 271 | DominatorTree DT; 272 | AssumptionCache AC; 273 | DomConditionCache DC; 274 | TargetLibraryInfo TLI; 275 | LoopInfo LI; 276 | ScalarEvolution SE; 277 | LazyValueInfo LVI; 278 | DenseMap NonZeroCache; 279 | DenseMap KnownBitsCache; 280 | DenseMap BECount; 281 | 282 | FunctionAnalysisCache(Function &F, TargetLibraryInfoImpl &TLIImpl); 283 | FunctionAnalysisCache(const FunctionAnalysisCache &) = delete; 284 | KnownBits queryKnownBits(Value *V, const SimplifyQuery &SQ); 285 | bool queryNonZero(Value *V, const SimplifyQuery &SQ); 286 | }; 287 | 288 | struct Frame final { 289 | Function *Func; 290 | BasicBlock *BB; 291 | BasicBlock::iterator PC; 292 | SmallVector> Allocas; 293 | DenseMap ValueMap; 294 | std::optional RetVal; 295 | FunctionAnalysisCache *Cache; 296 | TargetLibraryInfo TLI; 297 | Frame *LastFrame; 298 | MemoryEffects MemEffects; 299 | std::stack LifetimeStack; 300 | 301 | explicit Frame(Function *Func, FunctionAnalysisCache *Cache, 302 | TargetLibraryInfoImpl &TLI, Frame *LastFrame, 303 | MemoryEffects ME); 304 | }; 305 | 306 | struct IntConstraintInfo final { 307 | ConstantRange Range; 308 | KnownBits Bits; 309 | bool HasPoison; 310 | 311 | explicit IntConstraintInfo(const std::optional &InitV) 312 | : Range(InitV.has_value() ? *InitV : APInt::getZero(32)), 313 | Bits(KnownBits::makeConstant(InitV.has_value() ? *InitV 314 | : APInt::getZero(32))), 315 | HasPoison(!InitV.has_value()) {} 316 | void update(const std::optional &V) { 317 | if (HasPoison) 318 | return; 319 | if (!V.has_value()) { 320 | HasPoison = true; 321 | return; 322 | } 323 | Range = Range.unionWith(*V); 324 | Bits = Bits.intersectWith(KnownBits::makeConstant(*V)); 325 | } 326 | }; 327 | 328 | struct EMITrackingInfo final { 329 | bool Enabled; 330 | bool EnablePGFTracking; 331 | DenseMap MayBeUndef; 332 | DenseMap Range; 333 | DenseMap NoWrapFlags; 334 | DenseMap TruncNoWrapFlags; 335 | DenseMap NNegFlags; 336 | DenseMap ICmpFlags; 337 | DenseMap IsPoisonFlags; 338 | DenseMap DisjointFlags; 339 | 340 | DenseMap> InterestingUses; 341 | DenseMap UseIntInfo; 342 | 343 | // TODO: nonnull 344 | // TODO: align 345 | // TODO: Use -> attributes mapping for arguments 346 | DenseSet ReachableBlocks; 347 | 348 | void trackRange(Value *K, const APInt &V) { 349 | if (V.getBitWidth() <= 1) 350 | return; 351 | if (!Range.contains(K)) 352 | Range.insert({K, V}); 353 | else { 354 | auto &Ref = Range.find(K)->second; 355 | Ref = Ref.unionWith(V); 356 | } 357 | } 358 | }; 359 | 360 | struct InterpreterOption { 361 | uint32_t VScale = 4; 362 | uint32_t MaxSteps = std::numeric_limits::max(); 363 | bool Verbose = false; 364 | bool DumpStackTrace = false; 365 | 366 | bool EnableEMITracking = false; 367 | bool EnablePGFTracking = true; 368 | bool EnableEMIDebugging = false; 369 | double EMIProb = 0.1; 370 | double EMIUseProb = 0.001; 371 | 372 | bool TrackVolatileMem = false; 373 | bool IgnoreParamAttrsOnIntrinsic = false; 374 | bool IgnoreExplicitLifetimeMarker = false; 375 | bool FillUninitializedMemWithPoison = false; 376 | bool StorePoisonIsNoop = false; 377 | bool StorePoisonIsImmUB = false; 378 | bool FreezeBytes = false; 379 | bool FuseFMulAdd = false; 380 | bool EnforceStackOrderLifetimeMarker = false; 381 | 382 | bool VerifyValueTracking = false; 383 | bool VerifySCEV = false; 384 | bool VerifyLazyValueInfo = false; 385 | bool ReduceMode = false; 386 | bool RustMode = false; 387 | }; 388 | 389 | class UBAwareInterpreter : public InstVisitor { 390 | LLVMContext &Ctx; 391 | Module &M; 392 | const DataLayout &DL; 393 | InterpreterOption Option; 394 | TargetLibraryInfoImpl TLI; 395 | MemoryManager MemMgr; 396 | std::shared_ptr NullPtrStorage; 397 | std::optional NullPtr; 398 | DenseMap> GlobalValues; 399 | std::unordered_set> AllocatedMems; 400 | DenseMap ValidCallees; 401 | DenseMap ValidBlockTargets; 402 | DenseMap> BlockTargets; 403 | DenseMap> ConstantCache; 404 | std::unordered_map> 405 | AnalysisCache; 406 | EMITrackingInfo EMIInfo; 407 | std::mt19937_64 Gen; 408 | Frame *CurrentFrame = nullptr; 409 | uint32_t Steps = 0; 410 | uint64_t VolatileMemHash = 0; 411 | 412 | SimplifyQuery getSQ(const Instruction *CxtI) const; 413 | void verifyValueTracking(Value *V, const AnyValue &RV, 414 | const Instruction *CxtI); 415 | void verifySCEV(Value *V, const AnyValue &RV); 416 | uint32_t getVectorLength(VectorType *Ty) const; 417 | uint32_t getFixedSize(TypeSize Size) const; 418 | AnyValue getPoison(Type *Ty) const; 419 | AnyValue getZero(Type *Ty) const; 420 | AnyValue convertFromConstant(Constant *V) const; 421 | AnyValue bitcast(const AnyValue &V, Type *SrcTy, Type *DstTy) const; 422 | void store(MemObject &MO, uint32_t Offset, const AnyValue &V, Type *Ty); 423 | AnyValue load(const MemObject &MO, uint32_t Offset, Type *Ty); 424 | void store(const AnyValue &P, uint32_t Alignment, const AnyValue &V, Type *Ty, 425 | bool IsVolatile); 426 | AnyValue load(const AnyValue &P, uint32_t Alignment, Type *Ty, 427 | bool IsVolatile); 428 | SingleValue offsetPointer(const Pointer &Ptr, const APInt &Offset, 429 | GEPNoWrapFlags Flags) const; 430 | SingleValue alloc(const APInt &AllocSize, bool ZeroInitialize); 431 | 432 | public: 433 | explicit UBAwareInterpreter(Module &M, InterpreterOption Option); 434 | 435 | Frame *getCurrentFrame() const { return CurrentFrame; } 436 | const InterpreterOption &getOption() const { return Option; } 437 | bool addValue(Instruction &I, AnyValue Val); 438 | bool jumpTo(BasicBlock *To); 439 | const AnyValue &getValue(Value *V); 440 | std::optional getInt(const SingleValue &SV); 441 | std::optional getInt(Value *V); 442 | APInt getIntNonPoison(Value *V); 443 | enum class BooleanVal { Poison, False, True }; 444 | BooleanVal getBoolean(const SingleValue &SV); 445 | bool getBooleanNonPoison(const SingleValue &SV); 446 | BooleanVal getBoolean(Value *V); 447 | char *getRawPtr(const SingleValue &SV); 448 | char *getRawPtr(SingleValue SV, size_t Size, size_t Alignment, bool IsStore, 449 | bool IsVolatile); 450 | DenormalMode getCurrentDenormalMode(Type *Ty); 451 | 452 | void volatileMemOpTy(Type *Ty, bool IsStore); 453 | void volatileMemOp(size_t Size, bool IsStore); 454 | 455 | bool visitAllocaInst(AllocaInst &AI); 456 | AnyValue visitBinOp(Type *RetTy, const AnyValue &LHS, const AnyValue &RHS, 457 | const function_ref &Fn); 459 | bool visitBinOp(Instruction &I, 460 | const function_ref &Fn); 462 | AnyValue visitUnOp(Type *RetTy, const AnyValue &Val, 463 | const function_ref &Fn, 464 | bool PropagatesPoison = true); 465 | bool visitUnOp(Instruction &I, 466 | const function_ref &Fn, 467 | bool PropagatesPoison = true); 468 | AnyValue visitTriOp( 469 | Type *RetTy, const AnyValue &X, const AnyValue &Y, const AnyValue &Z, 470 | const function_ref &Fn); 472 | 473 | bool visitICmpInst(ICmpInst &I); 474 | AnyValue visitIntBinOp( 475 | Type *RetTy, const AnyValue &LHS, const AnyValue &RHS, 476 | const function_ref(const APInt &, const APInt &)> 477 | &Fn); 478 | AnyValue 479 | visitFPBinOp(Type *RetTy, FastMathFlags FMF, const AnyValue &LHS, 480 | const AnyValue &RHS, 481 | const function_ref(const APFloat &, 482 | const APFloat &)> &Fn); 483 | bool visitIntBinOp(Instruction &I, const function_ref( 484 | const APInt &, const APInt &)> &Fn); 485 | bool visitFPBinOp(Instruction &I, const function_ref( 486 | const APFloat &, const APFloat &)> &Fn); 487 | AnyValue visitIntTriOp(Type *RetTy, const AnyValue &X, const AnyValue &Y, 488 | const AnyValue &Z, 489 | const function_ref( 490 | const APInt &, const APInt &, const APInt &)> &Fn); 491 | AnyValue 492 | visitFPTriOp(Type *RetTy, FastMathFlags FMF, const AnyValue &X, 493 | const AnyValue &Y, const AnyValue &Z, 494 | const function_ref( 495 | const APFloat &, const APFloat &, const APFloat &)> &Fn); 496 | bool visitAnd(BinaryOperator &I); 497 | bool visitXor(BinaryOperator &I); 498 | bool visitOr(BinaryOperator &I); 499 | bool visitShl(BinaryOperator &I); 500 | bool visitLShr(BinaryOperator &I); 501 | bool visitAShr(BinaryOperator &I); 502 | bool visitAdd(BinaryOperator &I); 503 | bool visitSub(BinaryOperator &I); 504 | bool visitMul(BinaryOperator &I); 505 | bool visitSDiv(BinaryOperator &I); 506 | bool visitSRem(BinaryOperator &I); 507 | bool visitUDiv(BinaryOperator &I); 508 | bool visitURem(BinaryOperator &I); 509 | AnyValue 510 | visitIntUnOp(Type *Ty, const AnyValue &Val, 511 | const function_ref(const APInt &)> &Fn); 512 | bool 513 | visitIntUnOp(Instruction &I, 514 | const function_ref(const APInt &)> &Fn); 515 | AnyValue 516 | visitFPUnOp(Type *RetTy, FastMathFlags FMF, const AnyValue &Val, 517 | const function_ref(const APFloat &)> &Fn); 518 | bool 519 | visitFPUnOp(Instruction &I, 520 | const function_ref(const APFloat &)> &Fn); 521 | bool visitTruncInst(TruncInst &Trunc); 522 | bool visitSExtInst(SExtInst &SExt); 523 | bool visitZExtInst(ZExtInst &ZExt); 524 | bool fpCast(Instruction &I); 525 | bool visitFPExtInst(FPExtInst &FPExt); 526 | bool visitFPTruncInst(FPTruncInst &FPTrunc); 527 | bool visitIntToFPInst(Instruction &I, bool IsSigned); 528 | bool visitSIToFPInst(SIToFPInst &I); 529 | bool visitUIToFPInst(UIToFPInst &I); 530 | bool visitFPToIntInst(Instruction &I, bool IsSigned); 531 | bool visitFPToSIInst(FPToSIInst &I); 532 | bool visitFPToUIInst(FPToUIInst &I); 533 | bool visitFNeg(UnaryOperator &I); 534 | bool visitFAdd(BinaryOperator &I); 535 | bool visitFSub(BinaryOperator &I); 536 | bool visitFMul(BinaryOperator &I); 537 | bool visitFDiv(BinaryOperator &I); 538 | bool visitFRem(BinaryOperator &I); 539 | bool visitFCmpInst(FCmpInst &FCmp); 540 | AnyValue freezeValue(const AnyValue &Val, Type *Ty); 541 | bool visitFreezeInst(FreezeInst &Freeze); 542 | bool visitSelect(SelectInst &SI); 543 | bool visitBranchInst(BranchInst &BI); 544 | bool visitIndirectBrInst(IndirectBrInst &IBI); 545 | SingleValue computeGEP(const SingleValue &Base, const APInt &Offset, 546 | GEPNoWrapFlags Flags); 547 | bool visitGetElementPtrInst(GetElementPtrInst &GEP); 548 | bool visitExtractValueInst(ExtractValueInst &EVI); 549 | bool visitInsertValueInst(InsertValueInst &IVI); 550 | bool visitInsertElementInst(InsertElementInst &IEI); 551 | bool visitExtractElementInst(ExtractElementInst &EEI); 552 | bool visitShuffleVectorInst(ShuffleVectorInst &SVI); 553 | bool visitStoreInst(StoreInst &SI); 554 | void handleRangeMetadata(AnyValue &V, Instruction &I); 555 | bool visitLoadInst(LoadInst &LI); 556 | void writeBits(APInt &Dst, uint32_t &Offset, const APInt &Src) const; 557 | void toBits(APInt &Bits, APInt &PoisonBits, uint32_t &Offset, 558 | const AnyValue &Val, Type *Ty) const; 559 | bool visitIntToPtr(IntToPtrInst &I); 560 | bool visitPtrToInt(PtrToIntInst &I); 561 | bool visitPtrToAddr(PtrToAddrInst &I); 562 | APInt readBits(const APInt &Src, uint32_t &Offset, uint32_t Width) const; 563 | AnyValue fromBits(const APInt &Bits, const APInt &PoisonBits, 564 | uint32_t &Offset, Type *Ty) const; 565 | bool visitBitCastInst(BitCastInst &BCI); 566 | std::string getValueName(Value *V); 567 | AnyValue handleCall(CallBase &CB); 568 | bool visitCallInst(CallInst &CI); 569 | bool visitCallBrInst(CallBrInst &CI); 570 | bool visitInvokeInst(InvokeInst &II); 571 | bool visitReturnInst(ReturnInst &RI); 572 | bool visitUnreachableInst(UnreachableInst &); 573 | bool visitSwitchInst(SwitchInst &SI); 574 | bool visitInstruction(Instruction &I); 575 | AnyValue handleWithOverflow( 576 | Type *OpTy, const AnyValue &LHS, const AnyValue &RHS, 577 | const function_ref(const APInt &, const APInt &)> 578 | &Fn); 579 | 580 | AnyValue callIntrinsic(IntrinsicInst &II, SmallVectorImpl &Args); 581 | AnyValue callLibFunc(LibFunc Func, Function *FuncDecl, 582 | SmallVectorImpl &Args); 583 | void patchRustLibFunc(); 584 | AnyValue call(Function *Func, CallBase *CB, SmallVectorImpl &Args); 585 | void dumpStackTrace(); 586 | int32_t runMain(); 587 | void mutate(); 588 | bool simplify(); 589 | }; 590 | --------------------------------------------------------------------------------