Selaa lähdekoodia

feat: refactor all the code

Shellmiao 9 kuukautta sitten
vanhempi
commit
075cd2481e
43 muutettua tiedostoa jossa 5469 lisäystä ja 7082 poistoa
  1. 26 0
      .gitignore
  2. 4 0
      README.md
  3. 0 7
      Scripts/CallGraphPassScript.sh
  4. 0 7
      Scripts/CompileCallGraphScript.sh
  5. 11 1
      Scripts/CompileModuleFusionScript.sh
  6. 0 7
      Scripts/CompileSliceScript.sh
  7. 1 1
      Scripts/ModuleFusionScript.sh
  8. 0 7
      Scripts/SliceFusionScript.sh
  9. BIN
      build/CallGraphPass.so
  10. BIN
      build/ModuleFusion.so
  11. BIN
      build/SliceFusionPass.so
  12. BIN
      combine_output/combined.bc
  13. 44 221
      combine_output/combined.ll
  14. BIN
      combine_output/projectB.bc
  15. 49 226
      combine_output/projectB.ll
  16. 18 18
      data/projectB.c
  17. BIN
      output/fused.ll
  18. BIN
      output/graph.ll
  19. 0 168
      output/log.txt
  20. 0 38
      output/log_graph.txt
  21. 221 219
      output/log_module_fusion.txt
  22. BIN
      output/module_fusion.bc
  23. 2140 2006
      output/module_fusion_text.cbe.c
  24. 0 475
      output/module_fusion_text.cbe_bak.c
  25. 714 511
      output/module_fusion_text.ll
  26. BIN
      proprocess_output/combined_tagged.bc
  27. 44 221
      proprocess_output/combined_tagged.ll
  28. BIN
      proprocess_output/projectB_tagged.bc
  29. 0 368
      src/CallGraphPass.cpp
  30. 1028 0
      src/Fusion/Fusion.cpp
  31. 65 0
      src/Fusion/Fusion.h
  32. 430 0
      src/Fusion/SliceAnalyzer.cpp
  33. 32 0
      src/Fusion/SliceAnalyzer.h
  34. 0 157
      src/LogSystem.h
  35. 43 2015
      src/ModuleFusion.cpp
  36. 0 409
      src/SliceFusionPass.cpp
  37. 319 0
      src/Util/CallGraphManager.cpp
  38. 64 0
      src/Util/CallGraphManager.h
  39. 45 0
      src/Util/LogSystem.cpp
  40. 62 0
      src/Util/LogSystem.h
  41. 75 0
      src/Util/LogSystem.inl
  42. 23 0
      src/Util/Utils.cpp
  43. 11 0
      src/Util/Utils.h

+ 26 - 0
.gitignore

@@ -0,0 +1,26 @@
+# 输出目录
+output/
+output/**
+
+# 备份目录
+back_up/
+back_up/**
+
+# 构建目录
+build/
+build/**
+
+# Python相关
+__pycache__/
+*.py[cod]
+*$py.class
+
+# IDE相关
+.idea/
+.vscode/
+*.swp
+*.swo
+
+# 系统相关
+.DS_Store
+Thumbs.db

+ 4 - 0
README.md

@@ -8,3 +8,7 @@
 
 ## Fusion对照图
 ![fusion](./assets/fusion.jpg)
+
+TODO:
+- 给phi块添加返回值
+- 看fused_performSimpleCalculations返回值为什么有问题

+ 0 - 7
Scripts/CallGraphPassScript.sh

@@ -1,7 +0,0 @@
-#!/bin/bash
-# 获取脚本所在目录
-SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
-# 切换到项目根目录
-cd "$SCRIPT_DIR/.."
-
-opt -load ./build/CallGraphPass.so -codefusion < proprocess_output/combined_tagged.ll > output/graph.ll 2> output/log_graph.txt

+ 0 - 7
Scripts/CompileCallGraphScript.sh

@@ -1,7 +0,0 @@
-#!/bin/bash
-# 获取脚本所在目录
-SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
-# 切换到项目根目录
-cd "$SCRIPT_DIR/.."
-
-clang++ -fPIC -shared src/CallGraphPass.cpp `llvm-config --cxxflags --ldflags` -o build/CallGraphPass.so

+ 11 - 1
Scripts/CompileModuleFusionScript.sh

@@ -4,4 +4,14 @@ SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
 # 切换到项目根目录
 cd "$SCRIPT_DIR/.."
 
-clang++ -fPIC -shared src/ModuleFusion.cpp `llvm-config --cxxflags --ldflags` -o build/ModuleFusion.so
+clang++ -fPIC -shared \
+    src/ModuleFusion.cpp \
+    src/Util/LogSystem.cpp \
+    src/Util/CallGraphManager.cpp \
+    src/Util/Utils.cpp \
+    src/Fusion/SliceAnalyzer.cpp \
+    src/Fusion/Fusion.cpp \
+    -I./src \
+    `llvm-config --cxxflags --ldflags --libs core analysis passes support` \
+    -Wl,--no-undefined \
+    -o build/ModuleFusion.so

+ 0 - 7
Scripts/CompileSliceScript.sh

@@ -1,7 +0,0 @@
-#!/bin/bash
-# 获取脚本所在目录
-SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
-# 切换到项目根目录
-cd "$SCRIPT_DIR/.."
-
-clang++ -fPIC -shared src/SliceFusionPass.cpp `llvm-config --cxxflags --ldflags` -o build/SliceFusionPass.so

+ 1 - 1
Scripts/ModuleFusionScript.sh

@@ -4,7 +4,7 @@ SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
 # 切换到项目根目录
 cd "$SCRIPT_DIR/.."
 
-opt -load ./build/ModuleFusion.so -codefusion < proprocess_output/combined_tagged.ll > output/module_fusion.bc 2> output/log_module_fusion.txt
+opt -load ./build/ModuleFusion.so -codefusion proprocess_output/combined_tagged.ll -o output/module_fusion.bc 2> output/log_module_fusion.txt
 
 llvm-dis output/module_fusion.bc -o output/module_fusion_text.ll
 llvm-cbe output/module_fusion_text.ll

+ 0 - 7
Scripts/SliceFusionScript.sh

@@ -1,7 +0,0 @@
-#!/bin/bash
-# 获取脚本所在目录
-SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
-# 切换到项目根目录
-cd "$SCRIPT_DIR/.."
-
-opt -load ./build/SliceFusionPass.so -codefusion < proprocess_output/combined_tagged.ll > output/fused.ll 2> output/log.txt

BIN
build/CallGraphPass.so


BIN
build/ModuleFusion.so


BIN
build/SliceFusionPass.so


BIN
combine_output/combined.bc


+ 44 - 221
combine_output/combined.ll

@@ -3059,159 +3059,6 @@ define dso_local void @reverseString(i8* %0) #0 {
 ; Function Attrs: nounwind readonly
 declare dso_local i64 @strlen(i8*) #5
 
-; Function Attrs: noinline nounwind optnone uwtable
-define dso_local i32 @longestIncreasingSubsequence(i32* %0, i32 %1) #0 {
-  %3 = alloca i32*, align 8
-  %4 = alloca i32, align 4
-  %5 = alloca [100 x i32], align 16
-  %6 = alloca i32, align 4
-  %7 = alloca i32, align 4
-  %8 = alloca i32, align 4
-  %9 = alloca i32, align 4
-  %10 = alloca i32, align 4
-  store i32* %0, i32** %3, align 8
-  store i32 %1, i32* %4, align 4
-  store i32 0, i32* %6, align 4
-  br label %11
-
-11:                                               ; preds = %19, %2
-  %12 = load i32, i32* %6, align 4
-  %13 = load i32, i32* %4, align 4
-  %14 = icmp slt i32 %12, %13
-  br i1 %14, label %15, label %22
-
-15:                                               ; preds = %11
-  %16 = load i32, i32* %6, align 4
-  %17 = sext i32 %16 to i64
-  %18 = getelementptr inbounds [100 x i32], [100 x i32]* %5, i64 0, i64 %17
-  store i32 1, i32* %18, align 4
-  br label %19
-
-19:                                               ; preds = %15
-  %20 = load i32, i32* %6, align 4
-  %21 = add nsw i32 %20, 1
-  store i32 %21, i32* %6, align 4
-  br label %11
-
-22:                                               ; preds = %11
-  store i32 1, i32* %7, align 4
-  br label %23
-
-23:                                               ; preds = %69, %22
-  %24 = load i32, i32* %7, align 4
-  %25 = load i32, i32* %4, align 4
-  %26 = icmp slt i32 %24, %25
-  br i1 %26, label %27, label %72
-
-27:                                               ; preds = %23
-  store i32 0, i32* %8, align 4
-  br label %28
-
-28:                                               ; preds = %65, %27
-  %29 = load i32, i32* %8, align 4
-  %30 = load i32, i32* %7, align 4
-  %31 = icmp slt i32 %29, %30
-  br i1 %31, label %32, label %68
-
-32:                                               ; preds = %28
-  %33 = load i32*, i32** %3, align 8
-  %34 = load i32, i32* %7, align 4
-  %35 = sext i32 %34 to i64
-  %36 = getelementptr inbounds i32, i32* %33, i64 %35
-  %37 = load i32, i32* %36, align 4
-  %38 = load i32*, i32** %3, align 8
-  %39 = load i32, i32* %8, align 4
-  %40 = sext i32 %39 to i64
-  %41 = getelementptr inbounds i32, i32* %38, i64 %40
-  %42 = load i32, i32* %41, align 4
-  %43 = icmp sgt i32 %37, %42
-  br i1 %43, label %44, label %64
-
-44:                                               ; preds = %32
-  %45 = load i32, i32* %7, align 4
-  %46 = sext i32 %45 to i64
-  %47 = getelementptr inbounds [100 x i32], [100 x i32]* %5, i64 0, i64 %46
-  %48 = load i32, i32* %47, align 4
-  %49 = load i32, i32* %8, align 4
-  %50 = sext i32 %49 to i64
-  %51 = getelementptr inbounds [100 x i32], [100 x i32]* %5, i64 0, i64 %50
-  %52 = load i32, i32* %51, align 4
-  %53 = add nsw i32 %52, 1
-  %54 = icmp slt i32 %48, %53
-  br i1 %54, label %55, label %64
-
-55:                                               ; preds = %44
-  %56 = load i32, i32* %8, align 4
-  %57 = sext i32 %56 to i64
-  %58 = getelementptr inbounds [100 x i32], [100 x i32]* %5, i64 0, i64 %57
-  %59 = load i32, i32* %58, align 4
-  %60 = add nsw i32 %59, 1
-  %61 = load i32, i32* %7, align 4
-  %62 = sext i32 %61 to i64
-  %63 = getelementptr inbounds [100 x i32], [100 x i32]* %5, i64 0, i64 %62
-  store i32 %60, i32* %63, align 4
-  br label %64
-
-64:                                               ; preds = %55, %44, %32
-  br label %65
-
-65:                                               ; preds = %64
-  %66 = load i32, i32* %8, align 4
-  %67 = add nsw i32 %66, 1
-  store i32 %67, i32* %8, align 4
-  br label %28
-
-68:                                               ; preds = %28
-  br label %69
-
-69:                                               ; preds = %68
-  %70 = load i32, i32* %7, align 4
-  %71 = add nsw i32 %70, 1
-  store i32 %71, i32* %7, align 4
-  br label %23
-
-72:                                               ; preds = %23
-  store i32 0, i32* %9, align 4
-  store i32 0, i32* %10, align 4
-  br label %73
-
-73:                                               ; preds = %90, %72
-  %74 = load i32, i32* %10, align 4
-  %75 = load i32, i32* %4, align 4
-  %76 = icmp slt i32 %74, %75
-  br i1 %76, label %77, label %93
-
-77:                                               ; preds = %73
-  %78 = load i32, i32* %9, align 4
-  %79 = load i32, i32* %10, align 4
-  %80 = sext i32 %79 to i64
-  %81 = getelementptr inbounds [100 x i32], [100 x i32]* %5, i64 0, i64 %80
-  %82 = load i32, i32* %81, align 4
-  %83 = icmp slt i32 %78, %82
-  br i1 %83, label %84, label %89
-
-84:                                               ; preds = %77
-  %85 = load i32, i32* %10, align 4
-  %86 = sext i32 %85 to i64
-  %87 = getelementptr inbounds [100 x i32], [100 x i32]* %5, i64 0, i64 %86
-  %88 = load i32, i32* %87, align 4
-  store i32 %88, i32* %9, align 4
-  br label %89
-
-89:                                               ; preds = %84, %77
-  br label %90
-
-90:                                               ; preds = %89
-  %91 = load i32, i32* %10, align 4
-  %92 = add nsw i32 %91, 1
-  store i32 %92, i32* %10, align 4
-  br label %73
-
-93:                                               ; preds = %73
-  %94 = load i32, i32* %9, align 4
-  ret i32 %94
-}
-
 ; Function Attrs: noinline nounwind optnone uwtable
 define dso_local i32 @testPoints(i32 %0) #0 {
   %2 = alloca i32, align 4
@@ -3473,83 +3320,59 @@ define dso_local i32 @projectB_main() #0 {
   %1 = alloca [14 x i8], align 1
   %2 = alloca [8 x i32], align 16
   %3 = alloca i32, align 4
-  %4 = alloca i32, align 4
-  %5 = alloca [100 x [100 x i32]], align 16
+  %4 = alloca [100 x [100 x i32]], align 16
+  %5 = alloca i32, align 4
   %6 = alloca i32, align 4
   %7 = alloca i32, align 4
-  %8 = alloca i32, align 4
-  %9 = call i32 @testPoints(i32 5)
+  %8 = call i32 @testPoints(i32 5)
   call void @llvm.memset.p0i8.i64(i8* align 16 bitcast ([100 x i32]* @cache to i8*), i8 -1, i64 400, i1 false)
-  %10 = bitcast [14 x i8]* %1 to i8*
-  call void @llvm.memcpy.p0i8.p0i8.i64(i8* align 1 %10, i8* align 1 getelementptr inbounds ([14 x i8], [14 x i8]* @__const.projectB_main.str, i32 0, i32 0), i64 14, i1 false)
-  %11 = getelementptr inbounds [14 x i8], [14 x i8]* %1, i64 0, i64 0
-  call void @reverseString(i8* %11)
-  %12 = bitcast [8 x i32]* %2 to i8*
-  call void @llvm.memcpy.p0i8.p0i8.i64(i8* align 16 %12, i8* align 16 bitcast ([8 x i32]* @__const.projectB_main.arr to i8*), i64 32, i1 false)
+  %9 = bitcast [14 x i8]* %1 to i8*
+  call void @llvm.memcpy.p0i8.p0i8.i64(i8* align 1 %9, i8* align 1 getelementptr inbounds ([14 x i8], [14 x i8]* @__const.projectB_main.str, i32 0, i32 0), i64 14, i1 false)
+  %10 = getelementptr inbounds [14 x i8], [14 x i8]* %1, i64 0, i64 0
+  call void @reverseString(i8* %10)
+  %11 = bitcast [8 x i32]* %2 to i8*
+  call void @llvm.memcpy.p0i8.p0i8.i64(i8* align 16 %11, i8* align 16 bitcast ([8 x i32]* @__const.projectB_main.arr to i8*), i64 32, i1 false)
   store i32 8, i32* %3, align 4
-  %13 = getelementptr inbounds [8 x i32], [8 x i32]* %2, i64 0, i64 0
-  %14 = load i32, i32* %3, align 4
-  %15 = call i32 @longestIncreasingSubsequence(i32* %13, i32 %14)
-  store i32 %15, i32* %4, align 4
-  %16 = bitcast [100 x [100 x i32]]* %5 to i8*
-  call void @llvm.memcpy.p0i8.p0i8.i64(i8* align 16 %16, i8* align 16 bitcast (<{ <{ i32, i32, i32, [97 x i32] }>, <{ i32, i32, i32, [97 x i32] }>, <{ i32, i32, i32, [97 x i32] }>, [97 x <{ i32, i32, i32, [97 x i32] }>] }>* @__const.projectB_main.matrix to i8*), i64 40000, i1 false)
-  %17 = getelementptr inbounds [100 x [100 x i32]], [100 x [100 x i32]]* %5, i64 0, i64 0
-  %18 = call i32 @processMatrix([100 x i32]* %17, i32 3)
-  store i32 %18, i32* %6, align 4
-  store i32 0, i32* %7, align 4
-  br label %19
-
-19:                                               ; preds = %24, %0
-  %20 = load i32, i32* %7, align 4
-  %21 = call i32 @memoizedFib(i32 %20)
-  %22 = load i32, i32* %7, align 4
-  %23 = add nsw i32 %22, 1
-  store i32 %23, i32* %7, align 4
-  br label %24
+  %12 = bitcast [100 x [100 x i32]]* %4 to i8*
+  call void @llvm.memcpy.p0i8.p0i8.i64(i8* align 16 %12, i8* align 16 bitcast (<{ <{ i32, i32, i32, [97 x i32] }>, <{ i32, i32, i32, [97 x i32] }>, <{ i32, i32, i32, [97 x i32] }>, [97 x <{ i32, i32, i32, [97 x i32] }>] }>* @__const.projectB_main.matrix to i8*), i64 40000, i1 false)
+  %13 = getelementptr inbounds [100 x [100 x i32]], [100 x [100 x i32]]* %4, i64 0, i64 0
+  %14 = call i32 @processMatrix([100 x i32]* %13, i32 3)
+  store i32 %14, i32* %5, align 4
+  store i32 0, i32* %6, align 4
+  br label %15
 
-24:                                               ; preds = %19
-  %25 = load i32, i32* %7, align 4
-  %26 = icmp slt i32 %25, 10
-  br i1 %26, label %19, label %27
+15:                                               ; preds = %20, %0
+  %16 = load i32, i32* %6, align 4
+  %17 = call i32 @memoizedFib(i32 %16)
+  %18 = load i32, i32* %6, align 4
+  %19 = add nsw i32 %18, 1
+  store i32 %19, i32* %6, align 4
+  br label %20
 
-27:                                               ; preds = %24
-  %28 = load i32, i32* %4, align 4
-  %29 = icmp sgt i32 %28, 5
-  br i1 %29, label %30, label %40
+20:                                               ; preds = %15
+  %21 = load i32, i32* %6, align 4
+  %22 = icmp slt i32 %21, 10
+  br i1 %22, label %15, label %23
 
-30:                                               ; preds = %27
-  %31 = load i32, i32* %6, align 4
-  %32 = icmp sgt i32 %31, 0
-  br i1 %32, label %33, label %36
+23:                                               ; preds = %20
+  %24 = load i32, i32* %5, align 4
+  %25 = icmp sgt i32 %24, 0
+  br i1 %25, label %26, label %28
 
-33:                                               ; preds = %30
-  %34 = load i32, i32* %4, align 4
-  %35 = call i32 @memoizedFib(i32 %34)
-  store i32 %35, i32* %8, align 4
-  br label %39
+26:                                               ; preds = %23
+  %27 = call i32 @memoizedFib(i32 7)
+  store i32 %27, i32* %7, align 4
+  br label %31
 
-36:                                               ; preds = %30
-  %37 = load i32, i32* %6, align 4
-  %38 = call i32 @countSetBits(i32 %37)
-  store i32 %38, i32* %8, align 4
-  br label %39
-
-39:                                               ; preds = %36, %33
-  br label %47
-
-40:                                               ; preds = %27
-  %41 = getelementptr inbounds [14 x i8], [14 x i8]* %1, i64 0, i64 0
-  %42 = call i64 @strlen(i8* %41) #10
-  %43 = load i32, i32* %6, align 4
-  %44 = sext i32 %43 to i64
-  %45 = add i64 %42, %44
-  %46 = trunc i64 %45 to i32
-  store i32 %46, i32* %8, align 4
-  br label %47
-
-47:                                               ; preds = %40, %39
-  %48 = load i32, i32* %8, align 4
-  ret i32 %48
+28:                                               ; preds = %23
+  %29 = load i32, i32* %5, align 4
+  %30 = call i32 @countSetBits(i32 %29)
+  store i32 %30, i32* %7, align 4
+  br label %31
+
+31:                                               ; preds = %28, %26
+  %32 = load i32, i32* %7, align 4
+  ret i32 %32
 }
 
 ; Function Attrs: argmemonly nounwind willreturn

BIN
combine_output/projectB.bc


+ 49 - 226
combine_output/projectB.ll

@@ -73,159 +73,6 @@ define dso_local void @reverseString(i8* %0) #0 {
 ; Function Attrs: nounwind readonly
 declare dso_local i64 @strlen(i8*) #1
 
-; Function Attrs: noinline nounwind optnone uwtable
-define dso_local i32 @longestIncreasingSubsequence(i32* %0, i32 %1) #0 {
-  %3 = alloca i32*, align 8
-  %4 = alloca i32, align 4
-  %5 = alloca [100 x i32], align 16
-  %6 = alloca i32, align 4
-  %7 = alloca i32, align 4
-  %8 = alloca i32, align 4
-  %9 = alloca i32, align 4
-  %10 = alloca i32, align 4
-  store i32* %0, i32** %3, align 8
-  store i32 %1, i32* %4, align 4
-  store i32 0, i32* %6, align 4
-  br label %11
-
-11:                                               ; preds = %19, %2
-  %12 = load i32, i32* %6, align 4
-  %13 = load i32, i32* %4, align 4
-  %14 = icmp slt i32 %12, %13
-  br i1 %14, label %15, label %22
-
-15:                                               ; preds = %11
-  %16 = load i32, i32* %6, align 4
-  %17 = sext i32 %16 to i64
-  %18 = getelementptr inbounds [100 x i32], [100 x i32]* %5, i64 0, i64 %17
-  store i32 1, i32* %18, align 4
-  br label %19
-
-19:                                               ; preds = %15
-  %20 = load i32, i32* %6, align 4
-  %21 = add nsw i32 %20, 1
-  store i32 %21, i32* %6, align 4
-  br label %11
-
-22:                                               ; preds = %11
-  store i32 1, i32* %7, align 4
-  br label %23
-
-23:                                               ; preds = %69, %22
-  %24 = load i32, i32* %7, align 4
-  %25 = load i32, i32* %4, align 4
-  %26 = icmp slt i32 %24, %25
-  br i1 %26, label %27, label %72
-
-27:                                               ; preds = %23
-  store i32 0, i32* %8, align 4
-  br label %28
-
-28:                                               ; preds = %65, %27
-  %29 = load i32, i32* %8, align 4
-  %30 = load i32, i32* %7, align 4
-  %31 = icmp slt i32 %29, %30
-  br i1 %31, label %32, label %68
-
-32:                                               ; preds = %28
-  %33 = load i32*, i32** %3, align 8
-  %34 = load i32, i32* %7, align 4
-  %35 = sext i32 %34 to i64
-  %36 = getelementptr inbounds i32, i32* %33, i64 %35
-  %37 = load i32, i32* %36, align 4
-  %38 = load i32*, i32** %3, align 8
-  %39 = load i32, i32* %8, align 4
-  %40 = sext i32 %39 to i64
-  %41 = getelementptr inbounds i32, i32* %38, i64 %40
-  %42 = load i32, i32* %41, align 4
-  %43 = icmp sgt i32 %37, %42
-  br i1 %43, label %44, label %64
-
-44:                                               ; preds = %32
-  %45 = load i32, i32* %7, align 4
-  %46 = sext i32 %45 to i64
-  %47 = getelementptr inbounds [100 x i32], [100 x i32]* %5, i64 0, i64 %46
-  %48 = load i32, i32* %47, align 4
-  %49 = load i32, i32* %8, align 4
-  %50 = sext i32 %49 to i64
-  %51 = getelementptr inbounds [100 x i32], [100 x i32]* %5, i64 0, i64 %50
-  %52 = load i32, i32* %51, align 4
-  %53 = add nsw i32 %52, 1
-  %54 = icmp slt i32 %48, %53
-  br i1 %54, label %55, label %64
-
-55:                                               ; preds = %44
-  %56 = load i32, i32* %8, align 4
-  %57 = sext i32 %56 to i64
-  %58 = getelementptr inbounds [100 x i32], [100 x i32]* %5, i64 0, i64 %57
-  %59 = load i32, i32* %58, align 4
-  %60 = add nsw i32 %59, 1
-  %61 = load i32, i32* %7, align 4
-  %62 = sext i32 %61 to i64
-  %63 = getelementptr inbounds [100 x i32], [100 x i32]* %5, i64 0, i64 %62
-  store i32 %60, i32* %63, align 4
-  br label %64
-
-64:                                               ; preds = %55, %44, %32
-  br label %65
-
-65:                                               ; preds = %64
-  %66 = load i32, i32* %8, align 4
-  %67 = add nsw i32 %66, 1
-  store i32 %67, i32* %8, align 4
-  br label %28
-
-68:                                               ; preds = %28
-  br label %69
-
-69:                                               ; preds = %68
-  %70 = load i32, i32* %7, align 4
-  %71 = add nsw i32 %70, 1
-  store i32 %71, i32* %7, align 4
-  br label %23
-
-72:                                               ; preds = %23
-  store i32 0, i32* %9, align 4
-  store i32 0, i32* %10, align 4
-  br label %73
-
-73:                                               ; preds = %90, %72
-  %74 = load i32, i32* %10, align 4
-  %75 = load i32, i32* %4, align 4
-  %76 = icmp slt i32 %74, %75
-  br i1 %76, label %77, label %93
-
-77:                                               ; preds = %73
-  %78 = load i32, i32* %9, align 4
-  %79 = load i32, i32* %10, align 4
-  %80 = sext i32 %79 to i64
-  %81 = getelementptr inbounds [100 x i32], [100 x i32]* %5, i64 0, i64 %80
-  %82 = load i32, i32* %81, align 4
-  %83 = icmp slt i32 %78, %82
-  br i1 %83, label %84, label %89
-
-84:                                               ; preds = %77
-  %85 = load i32, i32* %10, align 4
-  %86 = sext i32 %85 to i64
-  %87 = getelementptr inbounds [100 x i32], [100 x i32]* %5, i64 0, i64 %86
-  %88 = load i32, i32* %87, align 4
-  store i32 %88, i32* %9, align 4
-  br label %89
-
-89:                                               ; preds = %84, %77
-  br label %90
-
-90:                                               ; preds = %89
-  %91 = load i32, i32* %10, align 4
-  %92 = add nsw i32 %91, 1
-  store i32 %92, i32* %10, align 4
-  br label %73
-
-93:                                               ; preds = %73
-  %94 = load i32, i32* %9, align 4
-  ret i32 %94
-}
-
 ; Function Attrs: noinline nounwind optnone uwtable
 define dso_local i32 @testPoints(i32 %0) #0 {
   %2 = alloca i32, align 4
@@ -487,83 +334,59 @@ define dso_local i32 @projectB_main() #0 {
   %1 = alloca [14 x i8], align 1
   %2 = alloca [8 x i32], align 16
   %3 = alloca i32, align 4
-  %4 = alloca i32, align 4
-  %5 = alloca [100 x [100 x i32]], align 16
+  %4 = alloca [100 x [100 x i32]], align 16
+  %5 = alloca i32, align 4
   %6 = alloca i32, align 4
   %7 = alloca i32, align 4
-  %8 = alloca i32, align 4
-  %9 = call i32 @testPoints(i32 5)
+  %8 = call i32 @testPoints(i32 5)
   call void @llvm.memset.p0i8.i64(i8* align 16 bitcast ([100 x i32]* @cache to i8*), i8 -1, i64 400, i1 false)
-  %10 = bitcast [14 x i8]* %1 to i8*
-  call void @llvm.memcpy.p0i8.p0i8.i64(i8* align 1 %10, i8* align 1 getelementptr inbounds ([14 x i8], [14 x i8]* @__const.projectB_main.str, i32 0, i32 0), i64 14, i1 false)
-  %11 = getelementptr inbounds [14 x i8], [14 x i8]* %1, i64 0, i64 0
-  call void @reverseString(i8* %11)
-  %12 = bitcast [8 x i32]* %2 to i8*
-  call void @llvm.memcpy.p0i8.p0i8.i64(i8* align 16 %12, i8* align 16 bitcast ([8 x i32]* @__const.projectB_main.arr to i8*), i64 32, i1 false)
+  %9 = bitcast [14 x i8]* %1 to i8*
+  call void @llvm.memcpy.p0i8.p0i8.i64(i8* align 1 %9, i8* align 1 getelementptr inbounds ([14 x i8], [14 x i8]* @__const.projectB_main.str, i32 0, i32 0), i64 14, i1 false)
+  %10 = getelementptr inbounds [14 x i8], [14 x i8]* %1, i64 0, i64 0
+  call void @reverseString(i8* %10)
+  %11 = bitcast [8 x i32]* %2 to i8*
+  call void @llvm.memcpy.p0i8.p0i8.i64(i8* align 16 %11, i8* align 16 bitcast ([8 x i32]* @__const.projectB_main.arr to i8*), i64 32, i1 false)
   store i32 8, i32* %3, align 4
-  %13 = getelementptr inbounds [8 x i32], [8 x i32]* %2, i64 0, i64 0
-  %14 = load i32, i32* %3, align 4
-  %15 = call i32 @longestIncreasingSubsequence(i32* %13, i32 %14)
-  store i32 %15, i32* %4, align 4
-  %16 = bitcast [100 x [100 x i32]]* %5 to i8*
-  call void @llvm.memcpy.p0i8.p0i8.i64(i8* align 16 %16, i8* align 16 bitcast (<{ <{ i32, i32, i32, [97 x i32] }>, <{ i32, i32, i32, [97 x i32] }>, <{ i32, i32, i32, [97 x i32] }>, [97 x <{ i32, i32, i32, [97 x i32] }>] }>* @__const.projectB_main.matrix to i8*), i64 40000, i1 false)
-  %17 = getelementptr inbounds [100 x [100 x i32]], [100 x [100 x i32]]* %5, i64 0, i64 0
-  %18 = call i32 @processMatrix([100 x i32]* %17, i32 3)
-  store i32 %18, i32* %6, align 4
-  store i32 0, i32* %7, align 4
-  br label %19
-
-19:                                               ; preds = %24, %0
-  %20 = load i32, i32* %7, align 4
-  %21 = call i32 @memoizedFib(i32 %20)
-  %22 = load i32, i32* %7, align 4
-  %23 = add nsw i32 %22, 1
-  store i32 %23, i32* %7, align 4
-  br label %24
-
-24:                                               ; preds = %19
-  %25 = load i32, i32* %7, align 4
-  %26 = icmp slt i32 %25, 10
-  br i1 %26, label %19, label %27
-
-27:                                               ; preds = %24
-  %28 = load i32, i32* %4, align 4
-  %29 = icmp sgt i32 %28, 5
-  br i1 %29, label %30, label %40
-
-30:                                               ; preds = %27
-  %31 = load i32, i32* %6, align 4
-  %32 = icmp sgt i32 %31, 0
-  br i1 %32, label %33, label %36
-
-33:                                               ; preds = %30
-  %34 = load i32, i32* %4, align 4
-  %35 = call i32 @memoizedFib(i32 %34)
-  store i32 %35, i32* %8, align 4
-  br label %39
-
-36:                                               ; preds = %30
-  %37 = load i32, i32* %6, align 4
-  %38 = call i32 @countSetBits(i32 %37)
-  store i32 %38, i32* %8, align 4
-  br label %39
-
-39:                                               ; preds = %36, %33
-  br label %47
-
-40:                                               ; preds = %27
-  %41 = getelementptr inbounds [14 x i8], [14 x i8]* %1, i64 0, i64 0
-  %42 = call i64 @strlen(i8* %41) #3
-  %43 = load i32, i32* %6, align 4
-  %44 = sext i32 %43 to i64
-  %45 = add i64 %42, %44
-  %46 = trunc i64 %45 to i32
-  store i32 %46, i32* %8, align 4
-  br label %47
-
-47:                                               ; preds = %40, %39
-  %48 = load i32, i32* %8, align 4
-  ret i32 %48
+  %12 = bitcast [100 x [100 x i32]]* %4 to i8*
+  call void @llvm.memcpy.p0i8.p0i8.i64(i8* align 16 %12, i8* align 16 bitcast (<{ <{ i32, i32, i32, [97 x i32] }>, <{ i32, i32, i32, [97 x i32] }>, <{ i32, i32, i32, [97 x i32] }>, [97 x <{ i32, i32, i32, [97 x i32] }>] }>* @__const.projectB_main.matrix to i8*), i64 40000, i1 false)
+  %13 = getelementptr inbounds [100 x [100 x i32]], [100 x [100 x i32]]* %4, i64 0, i64 0
+  %14 = call i32 @processMatrix([100 x i32]* %13, i32 3)
+  store i32 %14, i32* %5, align 4
+  store i32 0, i32* %6, align 4
+  br label %15
+
+15:                                               ; preds = %20, %0
+  %16 = load i32, i32* %6, align 4
+  %17 = call i32 @memoizedFib(i32 %16)
+  %18 = load i32, i32* %6, align 4
+  %19 = add nsw i32 %18, 1
+  store i32 %19, i32* %6, align 4
+  br label %20
+
+20:                                               ; preds = %15
+  %21 = load i32, i32* %6, align 4
+  %22 = icmp slt i32 %21, 10
+  br i1 %22, label %15, label %23
+
+23:                                               ; preds = %20
+  %24 = load i32, i32* %5, align 4
+  %25 = icmp sgt i32 %24, 0
+  br i1 %25, label %26, label %28
+
+26:                                               ; preds = %23
+  %27 = call i32 @memoizedFib(i32 7)
+  store i32 %27, i32* %7, align 4
+  br label %31
+
+28:                                               ; preds = %23
+  %29 = load i32, i32* %5, align 4
+  %30 = call i32 @countSetBits(i32 %29)
+  store i32 %30, i32* %7, align 4
+  br label %31
+
+31:                                               ; preds = %28, %26
+  %32 = load i32, i32* %7, align 4
+  ret i32 %32
 }
 
 ; Function Attrs: argmemonly nounwind willreturn

+ 18 - 18
data/projectB.c

@@ -15,24 +15,24 @@ void reverseString(char* str) {
     }
 }
 
-// 动态规划函数
-int longestIncreasingSubsequence(int arr[], int size) {
-    int lis[MAX_SIZE];
-    for(int i = 0; i < size; i++)
-        lis[i] = 1;
+// // 动态规划函数
+// int longestIncreasingSubsequence(int arr[], int size) {
+//     int lis[MAX_SIZE];
+//     for(int i = 0; i < size; i++)
+//         lis[i] = 1;
         
-    for(int i = 1; i < size; i++)
-        for(int j = 0; j < i; j++)
-            if(arr[i] > arr[j] && lis[i] < lis[j] + 1)
-                lis[i] = lis[j] + 1;
+//     for(int i = 1; i < size; i++)
+//         for(int j = 0; j < i; j++)
+//             if(arr[i] > arr[j] && lis[i] < lis[j] + 1)
+//                 lis[i] = lis[j] + 1;
                 
-    int max = 0;
-    for(int i = 0; i < size; i++)
-        if(max < lis[i])
-            max = lis[i];
+//     int max = 0;
+//     for(int i = 0; i < size; i++)
+//         if(max < lis[i])
+//             max = lis[i];
             
-    return max;
-}
+//     return max;
+// }
 
 int testPoints(int n) {
     int count = 0;
@@ -95,7 +95,7 @@ int main() {
     // 动态规划
     int arr[] = {10, 22, 9, 33, 21, 50, 41, 60};
     int size = sizeof(arr)/sizeof(arr[0]);
-    int lis = longestIncreasingSubsequence(arr, size);
+    // int lis = longestIncreasingSubsequence(arr, size);
     
     // 矩阵处理
     int matrix[MAX_SIZE][MAX_SIZE] = {{1,2,3},{4,5,6},{7,8,9}};
@@ -110,9 +110,9 @@ int main() {
     
     // 复杂条件判断
     int result;
-    if(lis > 5) {
+    if(7 > 5) {
         if(matrixSum > 0) {
-            result = memoizedFib(lis);
+            result = memoizedFib(7);
         } else {
             result = countSetBits(matrixSum);
         }

BIN
output/fused.ll


BIN
output/graph.ll


+ 0 - 168
output/log.txt

@@ -1,168 +0,0 @@
-[INFO][factorial][isTargetCode] Checking if function 'factorial' is target code
-[INFO][factorial][isTargetCode] Function 'factorial' project: Bunker, isTarget: false
-[INFO][bubbleSort][isTargetCode] Checking if function 'bubbleSort' is target code
-[INFO][bubbleSort][isTargetCode] Function 'bubbleSort' project: Bunker, isTarget: false
-[INFO][calculateDistance][isTargetCode] Checking if function 'calculateDistance' is target code
-[INFO][calculateDistance][isTargetCode] Function 'calculateDistance' project: Bunker, isTarget: false
-[INFO][fibonacci][isTargetCode] Checking if function 'fibonacci' is target code
-[INFO][fibonacci][isTargetCode] Function 'fibonacci' project: Bunker, isTarget: false
-[INFO][projectA_main][isTargetCode] Checking if function 'projectA_main' is target code
-[INFO][projectA_main][isTargetCode] Function 'projectA_main' project: Bunker, isTarget: false
-[INFO][reverseString][isTargetCode] Checking if function 'reverseString' is target code
-[INFO][reverseString][isTargetCode] Function 'reverseString' project: Target, isTarget: true
-[DEBUG][reverseString][checkCriticalPoint] Starting critical point check: %1
-[DEBUG][reverseString][checkCriticalPoint] Block  critical status: yes
-[DEBUG][reverseString][checkCriticalPoint] Starting critical point check: %9
-[DEBUG][reverseString][checkCriticalPoint] Block  critical status: yes
-[DEBUG][reverseString][checkCriticalPoint] Starting critical point check: %14
-[DEBUG][reverseString][checkCriticalPoint] Block  critical status: no
-[DEBUG][reverseString][checkCriticalPoint] Starting critical point check: %40
-[DEBUG][reverseString][checkCriticalPoint] Block  critical status: no
-[DEBUG][reverseString][checkCriticalPoint] Starting critical point check: %43
-[DEBUG][reverseString][checkCriticalPoint] Block  critical status: yes
-[INFO][longestIncreasingSubsequence][isTargetCode] Checking if function 'longestIncreasingSubsequence' is target code
-[INFO][longestIncreasingSubsequence][isTargetCode] Function 'longestIncreasingSubsequence' project: Target, isTarget: true
-[DEBUG][longestIncreasingSubsequence][checkCriticalPoint] Starting critical point check: %2
-[DEBUG][longestIncreasingSubsequence][checkCriticalPoint] Block  critical status: yes
-[DEBUG][longestIncreasingSubsequence][checkCriticalPoint] Starting critical point check: %11
-[DEBUG][longestIncreasingSubsequence][checkCriticalPoint] Block  critical status: yes
-[DEBUG][longestIncreasingSubsequence][checkCriticalPoint] Starting critical point check: %15
-[DEBUG][longestIncreasingSubsequence][checkCriticalPoint] Block  critical status: no
-[DEBUG][longestIncreasingSubsequence][checkCriticalPoint] Starting critical point check: %19
-[DEBUG][longestIncreasingSubsequence][checkCriticalPoint] Block  critical status: no
-[DEBUG][longestIncreasingSubsequence][checkCriticalPoint] Starting critical point check: %22
-[DEBUG][longestIncreasingSubsequence][checkCriticalPoint] Block  critical status: yes
-[DEBUG][longestIncreasingSubsequence][checkCriticalPoint] Starting critical point check: %23
-[DEBUG][longestIncreasingSubsequence][checkCriticalPoint] Block  critical status: yes
-[DEBUG][longestIncreasingSubsequence][checkCriticalPoint] Starting critical point check: %27
-[DEBUG][longestIncreasingSubsequence][checkCriticalPoint] Block  critical status: no
-[DEBUG][longestIncreasingSubsequence][checkCriticalPoint] Starting critical point check: %28
-[DEBUG][longestIncreasingSubsequence][checkCriticalPoint] Block  critical status: no
-[DEBUG][longestIncreasingSubsequence][checkCriticalPoint] Starting critical point check: %32
-[DEBUG][longestIncreasingSubsequence][checkCriticalPoint] Block  critical status: no
-[DEBUG][longestIncreasingSubsequence][checkCriticalPoint] Starting critical point check: %44
-[DEBUG][longestIncreasingSubsequence][checkCriticalPoint] Block  critical status: no
-[DEBUG][longestIncreasingSubsequence][checkCriticalPoint] Starting critical point check: %55
-[DEBUG][longestIncreasingSubsequence][checkCriticalPoint] Block  critical status: no
-[DEBUG][longestIncreasingSubsequence][checkCriticalPoint] Starting critical point check: %64
-[DEBUG][longestIncreasingSubsequence][checkCriticalPoint] Block  critical status: no
-[DEBUG][longestIncreasingSubsequence][checkCriticalPoint] Starting critical point check: %65
-[DEBUG][longestIncreasingSubsequence][checkCriticalPoint] Block  critical status: no
-[DEBUG][longestIncreasingSubsequence][checkCriticalPoint] Starting critical point check: %68
-[DEBUG][longestIncreasingSubsequence][checkCriticalPoint] Block  critical status: no
-[DEBUG][longestIncreasingSubsequence][checkCriticalPoint] Starting critical point check: %69
-[DEBUG][longestIncreasingSubsequence][checkCriticalPoint] Block  critical status: no
-[DEBUG][longestIncreasingSubsequence][checkCriticalPoint] Starting critical point check: %72
-[DEBUG][longestIncreasingSubsequence][checkCriticalPoint] Block  critical status: yes
-[DEBUG][longestIncreasingSubsequence][checkCriticalPoint] Starting critical point check: %73
-[DEBUG][longestIncreasingSubsequence][checkCriticalPoint] Block  critical status: yes
-[DEBUG][longestIncreasingSubsequence][checkCriticalPoint] Starting critical point check: %77
-[DEBUG][longestIncreasingSubsequence][checkCriticalPoint] Block  critical status: no
-[DEBUG][longestIncreasingSubsequence][checkCriticalPoint] Starting critical point check: %84
-[DEBUG][longestIncreasingSubsequence][checkCriticalPoint] Block  critical status: no
-[DEBUG][longestIncreasingSubsequence][checkCriticalPoint] Starting critical point check: %89
-[DEBUG][longestIncreasingSubsequence][checkCriticalPoint] Block  critical status: no
-[DEBUG][longestIncreasingSubsequence][checkCriticalPoint] Starting critical point check: %90
-[DEBUG][longestIncreasingSubsequence][checkCriticalPoint] Block  critical status: no
-[DEBUG][longestIncreasingSubsequence][checkCriticalPoint] Starting critical point check: %93
-[DEBUG][longestIncreasingSubsequence][checkCriticalPoint] Block  critical status: yes
-[INFO][testPoints][isTargetCode] Checking if function 'testPoints' is target code
-[INFO][testPoints][isTargetCode] Function 'testPoints' project: Target, isTarget: true
-[DEBUG][testPoints][checkCriticalPoint] Starting critical point check: %1
-[DEBUG][testPoints][checkCriticalPoint] Block  critical status: yes
-[DEBUG][testPoints][checkCriticalPoint] Starting critical point check: %6
-[DEBUG][testPoints][checkCriticalPoint] Block  critical status: yes
-[DEBUG][testPoints][checkCriticalPoint] Starting critical point check: %9
-[DEBUG][testPoints][checkCriticalPoint] Block  critical status: no
-[DEBUG][testPoints][checkCriticalPoint] Starting critical point check: %14
-[DEBUG][testPoints][checkCriticalPoint] Block  critical status: no
-[DEBUG][testPoints][checkCriticalPoint] Starting critical point check: %15
-[DEBUG][testPoints][checkCriticalPoint] Block  critical status: no
-[DEBUG][testPoints][checkCriticalPoint] Starting critical point check: %16
-[DEBUG][testPoints][checkCriticalPoint] Block  critical status: no
-[DEBUG][testPoints][checkCriticalPoint] Starting critical point check: %19
-[DEBUG][testPoints][checkCriticalPoint] Block  critical status: no
-[DEBUG][testPoints][checkCriticalPoint] Starting critical point check: %21
-[DEBUG][testPoints][checkCriticalPoint] Block  critical status: yes
-[INFO][countSetBits][isTargetCode] Checking if function 'countSetBits' is target code
-[INFO][countSetBits][isTargetCode] Function 'countSetBits' project: Target, isTarget: true
-[DEBUG][countSetBits][checkCriticalPoint] Starting critical point check: %1
-[DEBUG][countSetBits][checkCriticalPoint] Block  critical status: yes
-[DEBUG][countSetBits][checkCriticalPoint] Starting critical point check: %4
-[DEBUG][countSetBits][checkCriticalPoint] Block  critical status: yes
-[DEBUG][countSetBits][checkCriticalPoint] Starting critical point check: %7
-[DEBUG][countSetBits][checkCriticalPoint] Block  critical status: no
-[DEBUG][countSetBits][checkCriticalPoint] Starting critical point check: %14
-[DEBUG][countSetBits][checkCriticalPoint] Block  critical status: yes
-[INFO][memoizedFib][isTargetCode] Checking if function 'memoizedFib' is target code
-[INFO][memoizedFib][isTargetCode] Function 'memoizedFib' project: Target, isTarget: true
-[DEBUG][memoizedFib][checkCriticalPoint] Starting critical point check: %1
-[DEBUG][memoizedFib][checkCriticalPoint] Block  critical status: yes
-[DEBUG][memoizedFib][checkCriticalPoint] Starting critical point check: %9
-[DEBUG][memoizedFib][checkCriticalPoint] Block  critical status: no
-[DEBUG][memoizedFib][checkCriticalPoint] Starting critical point check: %14
-[DEBUG][memoizedFib][checkCriticalPoint] Block  critical status: no
-[DEBUG][memoizedFib][checkCriticalPoint] Starting critical point check: %17
-[DEBUG][memoizedFib][checkCriticalPoint] Block  critical status: no
-[DEBUG][memoizedFib][checkCriticalPoint] Starting critical point check: %19
-[DEBUG][memoizedFib][checkCriticalPoint] Block  critical status: no
-[DEBUG][memoizedFib][checkCriticalPoint] Starting critical point check: %34
-[DEBUG][memoizedFib][checkCriticalPoint] Block  critical status: yes
-[INFO][processMatrix][isTargetCode] Checking if function 'processMatrix' is target code
-[INFO][processMatrix][isTargetCode] Function 'processMatrix' project: Target, isTarget: true
-[DEBUG][processMatrix][checkCriticalPoint] Starting critical point check: %2
-[DEBUG][processMatrix][checkCriticalPoint] Block  critical status: yes
-[DEBUG][processMatrix][checkCriticalPoint] Starting critical point check: %8
-[DEBUG][processMatrix][checkCriticalPoint] Block  critical status: yes
-[DEBUG][processMatrix][checkCriticalPoint] Starting critical point check: %12
-[DEBUG][processMatrix][checkCriticalPoint] Block  critical status: no
-[DEBUG][processMatrix][checkCriticalPoint] Starting critical point check: %13
-[DEBUG][processMatrix][checkCriticalPoint] Block  critical status: no
-[DEBUG][processMatrix][checkCriticalPoint] Starting critical point check: %17
-[DEBUG][processMatrix][checkCriticalPoint] Block  critical status: no
-[DEBUG][processMatrix][checkCriticalPoint] Starting critical point check: %21
-[DEBUG][processMatrix][checkCriticalPoint] Block  critical status: no
-[DEBUG][processMatrix][checkCriticalPoint] Starting critical point check: %32
-[DEBUG][processMatrix][checkCriticalPoint] Block  critical status: no
-[DEBUG][processMatrix][checkCriticalPoint] Starting critical point check: %43
-[DEBUG][processMatrix][checkCriticalPoint] Block  critical status: no
-[DEBUG][processMatrix][checkCriticalPoint] Starting critical point check: %54
-[DEBUG][processMatrix][checkCriticalPoint] Block  critical status: no
-[DEBUG][processMatrix][checkCriticalPoint] Starting critical point check: %55
-[DEBUG][processMatrix][checkCriticalPoint] Block  critical status: no
-[DEBUG][processMatrix][checkCriticalPoint] Starting critical point check: %59
-[DEBUG][processMatrix][checkCriticalPoint] Block  critical status: no
-[DEBUG][processMatrix][checkCriticalPoint] Starting critical point check: %71
-[DEBUG][processMatrix][checkCriticalPoint] Block  critical status: no
-[DEBUG][processMatrix][checkCriticalPoint] Starting critical point check: %72
-[DEBUG][processMatrix][checkCriticalPoint] Block  critical status: no
-[DEBUG][processMatrix][checkCriticalPoint] Starting critical point check: %73
-[DEBUG][processMatrix][checkCriticalPoint] Block  critical status: no
-[DEBUG][processMatrix][checkCriticalPoint] Starting critical point check: %76
-[DEBUG][processMatrix][checkCriticalPoint] Block  critical status: no
-[DEBUG][processMatrix][checkCriticalPoint] Starting critical point check: %77
-[DEBUG][processMatrix][checkCriticalPoint] Block  critical status: no
-[DEBUG][processMatrix][checkCriticalPoint] Starting critical point check: %80
-[DEBUG][processMatrix][checkCriticalPoint] Block  critical status: yes
-[INFO][projectB_main][isTargetCode] Checking if function 'projectB_main' is target code
-[INFO][projectB_main][isTargetCode] Function 'projectB_main' project: Target, isTarget: true
-[DEBUG][projectB_main][checkCriticalPoint] Starting critical point check: %0
-[DEBUG][projectB_main][checkCriticalPoint] Block  critical status: yes
-[DEBUG][projectB_main][checkCriticalPoint] Starting critical point check: %19
-[DEBUG][projectB_main][checkCriticalPoint] Block  critical status: yes
-[DEBUG][projectB_main][checkCriticalPoint] Starting critical point check: %24
-[DEBUG][projectB_main][checkCriticalPoint] Block  critical status: yes
-[DEBUG][projectB_main][checkCriticalPoint] Starting critical point check: %27
-[DEBUG][projectB_main][checkCriticalPoint] Block  critical status: yes
-[DEBUG][projectB_main][checkCriticalPoint] Starting critical point check: %30
-[DEBUG][projectB_main][checkCriticalPoint] Block  critical status: no
-[DEBUG][projectB_main][checkCriticalPoint] Starting critical point check: %33
-[DEBUG][projectB_main][checkCriticalPoint] Block  critical status: no
-[DEBUG][projectB_main][checkCriticalPoint] Starting critical point check: %36
-[DEBUG][projectB_main][checkCriticalPoint] Block  critical status: no
-[DEBUG][projectB_main][checkCriticalPoint] Starting critical point check: %39
-[DEBUG][projectB_main][checkCriticalPoint] Block  critical status: no
-[DEBUG][projectB_main][checkCriticalPoint] Starting critical point check: %40
-[DEBUG][projectB_main][checkCriticalPoint] Block  critical status: no
-[DEBUG][projectB_main][checkCriticalPoint] Starting critical point check: %47
-[DEBUG][projectB_main][checkCriticalPoint] Block  critical status: yes

+ 0 - 38
output/log_graph.txt

@@ -1,38 +0,0 @@
-```mermaid
-graph TD
-    %% Target Project Call Graph
-    countSetBits["countSetBits\nDepth: 2"]:::target
-    longestIncreasingSubsequence["longestIncreasingSubsequence\nDepth: 2"]:::target
-    memoizedFib["memoizedFib\nDepth: 2"]:::target
-    processMatrix["processMatrix\nDepth: 2"]:::target
-    projectB_main["projectB_main\nDepth: 1"]:::target
-    reverseString["reverseString\nDepth: 2"]:::target
-    testPoints["testPoints\nDepth: 2"]:::target
-    memoizedFib --> memoizedFib
-    processMatrix --> countSetBits
-    projectB_main --> countSetBits
-    projectB_main --> longestIncreasingSubsequence
-    projectB_main --> memoizedFib
-    projectB_main --> processMatrix
-    projectB_main --> reverseString
-    projectB_main --> testPoints
-    classDef target fill:#f96,stroke:#333,stroke-width:4px
-```
-
-```mermaid
-graph TD
-    %% Cover Project Call Graph
-    bubbleSort["bubbleSort\nDepth: 0"]
-    calculateDistance["calculateDistance\nDepth: 0"]
-    factorial["factorial\nDepth: 0"]
-    fibonacci["fibonacci\nDepth: 0"]
-    projectA_main["projectA_main\nDepth: 0"]
-    factorial --> factorial
-    fibonacci --> fibonacci
-    projectA_main --> bubbleSort
-    projectA_main --> calculateDistance
-    projectA_main --> factorial
-    projectA_main --> fibonacci
-    classDef target fill:#f96,stroke:#333,stroke-width:4px
-```
-

Tiedoston diff-näkymää rajattu, sillä se on liian suuri
+ 221 - 219
output/log_module_fusion.txt


BIN
output/module_fusion.bc


Tiedoston diff-näkymää rajattu, sillä se on liian suuri
+ 2140 - 2006
output/module_fusion_text.cbe.c


Tiedoston diff-näkymää rajattu, sillä se on liian suuri
+ 0 - 475
output/module_fusion_text.cbe_bak.c


Tiedoston diff-näkymää rajattu, sillä se on liian suuri
+ 714 - 511
output/module_fusion_text.ll


BIN
proprocess_output/combined_tagged.bc


+ 44 - 221
proprocess_output/combined_tagged.ll

@@ -3059,159 +3059,6 @@ define dso_local void @reverseString(i8* %0) #0 !project_source !3 {
 ; Function Attrs: nounwind readonly
 declare dso_local i64 @strlen(i8*) #5
 
-; Function Attrs: noinline nounwind optnone uwtable
-define dso_local i32 @longestIncreasingSubsequence(i32* %0, i32 %1) #0 !project_source !3 {
-  %3 = alloca i32*, align 8
-  %4 = alloca i32, align 4
-  %5 = alloca [100 x i32], align 16
-  %6 = alloca i32, align 4
-  %7 = alloca i32, align 4
-  %8 = alloca i32, align 4
-  %9 = alloca i32, align 4
-  %10 = alloca i32, align 4
-  store i32* %0, i32** %3, align 8
-  store i32 %1, i32* %4, align 4
-  store i32 0, i32* %6, align 4
-  br label %11
-
-11:                                               ; preds = %19, %2
-  %12 = load i32, i32* %6, align 4
-  %13 = load i32, i32* %4, align 4
-  %14 = icmp slt i32 %12, %13
-  br i1 %14, label %15, label %22
-
-15:                                               ; preds = %11
-  %16 = load i32, i32* %6, align 4
-  %17 = sext i32 %16 to i64
-  %18 = getelementptr inbounds [100 x i32], [100 x i32]* %5, i64 0, i64 %17
-  store i32 1, i32* %18, align 4
-  br label %19
-
-19:                                               ; preds = %15
-  %20 = load i32, i32* %6, align 4
-  %21 = add nsw i32 %20, 1
-  store i32 %21, i32* %6, align 4
-  br label %11
-
-22:                                               ; preds = %11
-  store i32 1, i32* %7, align 4
-  br label %23
-
-23:                                               ; preds = %69, %22
-  %24 = load i32, i32* %7, align 4
-  %25 = load i32, i32* %4, align 4
-  %26 = icmp slt i32 %24, %25
-  br i1 %26, label %27, label %72
-
-27:                                               ; preds = %23
-  store i32 0, i32* %8, align 4
-  br label %28
-
-28:                                               ; preds = %65, %27
-  %29 = load i32, i32* %8, align 4
-  %30 = load i32, i32* %7, align 4
-  %31 = icmp slt i32 %29, %30
-  br i1 %31, label %32, label %68
-
-32:                                               ; preds = %28
-  %33 = load i32*, i32** %3, align 8
-  %34 = load i32, i32* %7, align 4
-  %35 = sext i32 %34 to i64
-  %36 = getelementptr inbounds i32, i32* %33, i64 %35
-  %37 = load i32, i32* %36, align 4
-  %38 = load i32*, i32** %3, align 8
-  %39 = load i32, i32* %8, align 4
-  %40 = sext i32 %39 to i64
-  %41 = getelementptr inbounds i32, i32* %38, i64 %40
-  %42 = load i32, i32* %41, align 4
-  %43 = icmp sgt i32 %37, %42
-  br i1 %43, label %44, label %64
-
-44:                                               ; preds = %32
-  %45 = load i32, i32* %7, align 4
-  %46 = sext i32 %45 to i64
-  %47 = getelementptr inbounds [100 x i32], [100 x i32]* %5, i64 0, i64 %46
-  %48 = load i32, i32* %47, align 4
-  %49 = load i32, i32* %8, align 4
-  %50 = sext i32 %49 to i64
-  %51 = getelementptr inbounds [100 x i32], [100 x i32]* %5, i64 0, i64 %50
-  %52 = load i32, i32* %51, align 4
-  %53 = add nsw i32 %52, 1
-  %54 = icmp slt i32 %48, %53
-  br i1 %54, label %55, label %64
-
-55:                                               ; preds = %44
-  %56 = load i32, i32* %8, align 4
-  %57 = sext i32 %56 to i64
-  %58 = getelementptr inbounds [100 x i32], [100 x i32]* %5, i64 0, i64 %57
-  %59 = load i32, i32* %58, align 4
-  %60 = add nsw i32 %59, 1
-  %61 = load i32, i32* %7, align 4
-  %62 = sext i32 %61 to i64
-  %63 = getelementptr inbounds [100 x i32], [100 x i32]* %5, i64 0, i64 %62
-  store i32 %60, i32* %63, align 4
-  br label %64
-
-64:                                               ; preds = %55, %44, %32
-  br label %65
-
-65:                                               ; preds = %64
-  %66 = load i32, i32* %8, align 4
-  %67 = add nsw i32 %66, 1
-  store i32 %67, i32* %8, align 4
-  br label %28
-
-68:                                               ; preds = %28
-  br label %69
-
-69:                                               ; preds = %68
-  %70 = load i32, i32* %7, align 4
-  %71 = add nsw i32 %70, 1
-  store i32 %71, i32* %7, align 4
-  br label %23
-
-72:                                               ; preds = %23
-  store i32 0, i32* %9, align 4
-  store i32 0, i32* %10, align 4
-  br label %73
-
-73:                                               ; preds = %90, %72
-  %74 = load i32, i32* %10, align 4
-  %75 = load i32, i32* %4, align 4
-  %76 = icmp slt i32 %74, %75
-  br i1 %76, label %77, label %93
-
-77:                                               ; preds = %73
-  %78 = load i32, i32* %9, align 4
-  %79 = load i32, i32* %10, align 4
-  %80 = sext i32 %79 to i64
-  %81 = getelementptr inbounds [100 x i32], [100 x i32]* %5, i64 0, i64 %80
-  %82 = load i32, i32* %81, align 4
-  %83 = icmp slt i32 %78, %82
-  br i1 %83, label %84, label %89
-
-84:                                               ; preds = %77
-  %85 = load i32, i32* %10, align 4
-  %86 = sext i32 %85 to i64
-  %87 = getelementptr inbounds [100 x i32], [100 x i32]* %5, i64 0, i64 %86
-  %88 = load i32, i32* %87, align 4
-  store i32 %88, i32* %9, align 4
-  br label %89
-
-89:                                               ; preds = %84, %77
-  br label %90
-
-90:                                               ; preds = %89
-  %91 = load i32, i32* %10, align 4
-  %92 = add nsw i32 %91, 1
-  store i32 %92, i32* %10, align 4
-  br label %73
-
-93:                                               ; preds = %73
-  %94 = load i32, i32* %9, align 4
-  ret i32 %94
-}
-
 ; Function Attrs: noinline nounwind optnone uwtable
 define dso_local i32 @testPoints(i32 %0) #0 !project_source !3 {
   %2 = alloca i32, align 4
@@ -3473,83 +3320,59 @@ define dso_local i32 @projectB_main() #0 !project_source !3 {
   %1 = alloca [14 x i8], align 1
   %2 = alloca [8 x i32], align 16
   %3 = alloca i32, align 4
-  %4 = alloca i32, align 4
-  %5 = alloca [100 x [100 x i32]], align 16
+  %4 = alloca [100 x [100 x i32]], align 16
+  %5 = alloca i32, align 4
   %6 = alloca i32, align 4
   %7 = alloca i32, align 4
-  %8 = alloca i32, align 4
-  %9 = call i32 @testPoints(i32 5)
+  %8 = call i32 @testPoints(i32 5)
   call void @llvm.memset.p0i8.i64(i8* align 16 bitcast ([100 x i32]* @cache to i8*), i8 -1, i64 400, i1 false)
-  %10 = bitcast [14 x i8]* %1 to i8*
-  call void @llvm.memcpy.p0i8.p0i8.i64(i8* align 1 %10, i8* align 1 getelementptr inbounds ([14 x i8], [14 x i8]* @__const.projectB_main.str, i32 0, i32 0), i64 14, i1 false)
-  %11 = getelementptr inbounds [14 x i8], [14 x i8]* %1, i64 0, i64 0
-  call void @reverseString(i8* %11)
-  %12 = bitcast [8 x i32]* %2 to i8*
-  call void @llvm.memcpy.p0i8.p0i8.i64(i8* align 16 %12, i8* align 16 bitcast ([8 x i32]* @__const.projectB_main.arr to i8*), i64 32, i1 false)
+  %9 = bitcast [14 x i8]* %1 to i8*
+  call void @llvm.memcpy.p0i8.p0i8.i64(i8* align 1 %9, i8* align 1 getelementptr inbounds ([14 x i8], [14 x i8]* @__const.projectB_main.str, i32 0, i32 0), i64 14, i1 false)
+  %10 = getelementptr inbounds [14 x i8], [14 x i8]* %1, i64 0, i64 0
+  call void @reverseString(i8* %10)
+  %11 = bitcast [8 x i32]* %2 to i8*
+  call void @llvm.memcpy.p0i8.p0i8.i64(i8* align 16 %11, i8* align 16 bitcast ([8 x i32]* @__const.projectB_main.arr to i8*), i64 32, i1 false)
   store i32 8, i32* %3, align 4
-  %13 = getelementptr inbounds [8 x i32], [8 x i32]* %2, i64 0, i64 0
-  %14 = load i32, i32* %3, align 4
-  %15 = call i32 @longestIncreasingSubsequence(i32* %13, i32 %14)
-  store i32 %15, i32* %4, align 4
-  %16 = bitcast [100 x [100 x i32]]* %5 to i8*
-  call void @llvm.memcpy.p0i8.p0i8.i64(i8* align 16 %16, i8* align 16 bitcast (<{ <{ i32, i32, i32, [97 x i32] }>, <{ i32, i32, i32, [97 x i32] }>, <{ i32, i32, i32, [97 x i32] }>, [97 x <{ i32, i32, i32, [97 x i32] }>] }>* @__const.projectB_main.matrix to i8*), i64 40000, i1 false)
-  %17 = getelementptr inbounds [100 x [100 x i32]], [100 x [100 x i32]]* %5, i64 0, i64 0
-  %18 = call i32 @processMatrix([100 x i32]* %17, i32 3)
-  store i32 %18, i32* %6, align 4
-  store i32 0, i32* %7, align 4
-  br label %19
-
-19:                                               ; preds = %24, %0
-  %20 = load i32, i32* %7, align 4
-  %21 = call i32 @memoizedFib(i32 %20)
-  %22 = load i32, i32* %7, align 4
-  %23 = add nsw i32 %22, 1
-  store i32 %23, i32* %7, align 4
-  br label %24
+  %12 = bitcast [100 x [100 x i32]]* %4 to i8*
+  call void @llvm.memcpy.p0i8.p0i8.i64(i8* align 16 %12, i8* align 16 bitcast (<{ <{ i32, i32, i32, [97 x i32] }>, <{ i32, i32, i32, [97 x i32] }>, <{ i32, i32, i32, [97 x i32] }>, [97 x <{ i32, i32, i32, [97 x i32] }>] }>* @__const.projectB_main.matrix to i8*), i64 40000, i1 false)
+  %13 = getelementptr inbounds [100 x [100 x i32]], [100 x [100 x i32]]* %4, i64 0, i64 0
+  %14 = call i32 @processMatrix([100 x i32]* %13, i32 3)
+  store i32 %14, i32* %5, align 4
+  store i32 0, i32* %6, align 4
+  br label %15
 
-24:                                               ; preds = %19
-  %25 = load i32, i32* %7, align 4
-  %26 = icmp slt i32 %25, 10
-  br i1 %26, label %19, label %27
+15:                                               ; preds = %20, %0
+  %16 = load i32, i32* %6, align 4
+  %17 = call i32 @memoizedFib(i32 %16)
+  %18 = load i32, i32* %6, align 4
+  %19 = add nsw i32 %18, 1
+  store i32 %19, i32* %6, align 4
+  br label %20
 
-27:                                               ; preds = %24
-  %28 = load i32, i32* %4, align 4
-  %29 = icmp sgt i32 %28, 5
-  br i1 %29, label %30, label %40
+20:                                               ; preds = %15
+  %21 = load i32, i32* %6, align 4
+  %22 = icmp slt i32 %21, 10
+  br i1 %22, label %15, label %23
 
-30:                                               ; preds = %27
-  %31 = load i32, i32* %6, align 4
-  %32 = icmp sgt i32 %31, 0
-  br i1 %32, label %33, label %36
+23:                                               ; preds = %20
+  %24 = load i32, i32* %5, align 4
+  %25 = icmp sgt i32 %24, 0
+  br i1 %25, label %26, label %28
 
-33:                                               ; preds = %30
-  %34 = load i32, i32* %4, align 4
-  %35 = call i32 @memoizedFib(i32 %34)
-  store i32 %35, i32* %8, align 4
-  br label %39
+26:                                               ; preds = %23
+  %27 = call i32 @memoizedFib(i32 7)
+  store i32 %27, i32* %7, align 4
+  br label %31
 
-36:                                               ; preds = %30
-  %37 = load i32, i32* %6, align 4
-  %38 = call i32 @countSetBits(i32 %37)
-  store i32 %38, i32* %8, align 4
-  br label %39
-
-39:                                               ; preds = %36, %33
-  br label %47
-
-40:                                               ; preds = %27
-  %41 = getelementptr inbounds [14 x i8], [14 x i8]* %1, i64 0, i64 0
-  %42 = call i64 @strlen(i8* %41) #10
-  %43 = load i32, i32* %6, align 4
-  %44 = sext i32 %43 to i64
-  %45 = add i64 %42, %44
-  %46 = trunc i64 %45 to i32
-  store i32 %46, i32* %8, align 4
-  br label %47
-
-47:                                               ; preds = %40, %39
-  %48 = load i32, i32* %8, align 4
-  ret i32 %48
+28:                                               ; preds = %23
+  %29 = load i32, i32* %5, align 4
+  %30 = call i32 @countSetBits(i32 %29)
+  store i32 %30, i32* %7, align 4
+  br label %31
+
+31:                                               ; preds = %28, %26
+  %32 = load i32, i32* %7, align 4
+  ret i32 %32
 }
 
 ; Function Attrs: argmemonly nounwind willreturn

BIN
proprocess_output/projectB_tagged.bc


+ 0 - 368
src/CallGraphPass.cpp

@@ -1,368 +0,0 @@
-#include "llvm/Pass.h"
-#include "llvm/IR/Function.h"
-#include "llvm/IR/Module.h"
-#include "llvm/IR/BasicBlock.h"
-#include "llvm/IR/Instructions.h"
-#include "llvm/IR/LegacyPassManager.h"
-#include "llvm/Transforms/IPO/PassManagerBuilder.h"
-#include "llvm/Support/raw_ostream.h"
-#include "llvm/Analysis/CFG.h"
-#include "llvm/Analysis/CallGraph.h"
-#include "LogSystem.h"
-#include <vector>
-#include <map>
-#include <set>
-#include <queue>
-#include <algorithm>
-#include <string>
-
-using namespace llvm;
-
-namespace {
-    struct FunctionSignature {
-        unsigned inDegree;
-        unsigned outDegree;
-        unsigned depth;
-        std::vector<unsigned> callerDepths;
-        std::vector<unsigned> calleeDepths;
-
-        FunctionSignature() : inDegree(0), outDegree(0), depth(0) {}
-
-        bool operator==(const FunctionSignature& other) const {
-            return inDegree == other.inDegree &&
-                   outDegree == other.outDegree &&
-                   depth == other.depth &&
-                   callerDepths == other.callerDepths &&
-                   calleeDepths == other.calleeDepths;
-        }
-    };
-
-    // 函数调用图的节点结构
-    struct CallNode {
-        std::string name;
-        bool isTarget;
-        std::set<std::string> callers;
-        std::set<std::string> callees;
-        unsigned depth;  // 在调用树中的深度
-
-        CallNode() : name(""), isTarget(false), depth(0) {}
-        
-        CallNode(std::string n, bool target = false) 
-            : name(n), isTarget(target), depth(0) {}
-    };
-
-    struct CodeFusionPass : public ModulePass {
-    public:
-        static char ID;
-        CodeFusionPass() : ModulePass(ID) {}
-
-        bool runOnModule(Module &M) override {
-            auto& logger = logging::LogSystem::getInstance();
-            logger.setGlobalLevel(logging::LogLevel::DEBUG);
-            
-            LOG_INFO("runOnModule", "Starting analysis for module: {0}", M.getName().str());
-
-            // 识别所有目标函数
-            for (Function &F : M) {
-                if (!F.isDeclaration() && isTargetCode(F)) {
-                    targetFunctions.insert(F.getName().str());
-                }
-            }
-
-            // 构建完整的调用图
-            buildCallGraph(M);
-
-            // 计算每个函数的调用深度
-            calculateCallDepths();
-
-            // 生成调用图的可视化
-            generateCallGraphs();
-
-            // 分析相似结构
-            findSimilarStructures();
-
-            return false;
-        }
-
-    private:
-        std::map<std::string, CallNode> callGraph;
-        std::set<std::string> targetFunctions;
-        std::map<std::string, unsigned> maxCallDepths;
-
-        void buildCallGraph(Module &M) {
-            LOG_INFO("buildCallGraph", "Building complete call graph");
-
-            // 初始化所有函数节点
-            for (Function &F : M) {
-                if (!F.isDeclaration()) {
-                    std::string fname = F.getName().str();
-                    bool isTarget = targetFunctions.find(fname) != targetFunctions.end();
-                    callGraph.insert({fname, CallNode(fname, isTarget)});
-                }
-            }
-
-            // 分析函数调用关系
-            for (Function &F : M) {
-                if (!F.isDeclaration()) {
-                    std::string callerName = F.getName().str();
-                    
-                    for (BasicBlock &BB : F) {
-                        for (Instruction &I : BB) {
-                            if (CallInst *CI = dyn_cast<CallInst>(&I)) {
-                                Function *CalledF = CI->getCalledFunction();
-                                if (CalledF && !CalledF->isDeclaration()) {
-                                    std::string calleeName = CalledF->getName().str();
-                                    
-                                    // 更新调用关系
-                                    callGraph[callerName].callees.insert(calleeName);
-                                    callGraph[calleeName].callers.insert(callerName);
-                                    
-                                    LOG_DEBUG("buildCallGraph", 
-                                        "Found call: {0} -> {1}", callerName, calleeName);
-                                }
-                            }
-                        }
-                    }
-                }
-            }
-        }
-
-        void calculateCallDepths() {
-            LOG_INFO("calculateCallDepths", "Calculating call depths");
-
-            for (const std::string &targetFunc : targetFunctions) {
-                std::map<std::string, unsigned> depths;
-                std::queue<std::pair<std::string, unsigned>> queue;
-                std::set<std::string> visited;
-
-                queue.push(std::make_pair(targetFunc, 0));
-                visited.insert(targetFunc);
-
-                while (!queue.empty()) {
-                    std::string currentFunc = queue.front().first;
-                    unsigned depth = queue.front().second;
-                    queue.pop();
-
-                    depths[currentFunc] = depth;
-                    
-                    for (const std::string &caller : callGraph[currentFunc].callers) {
-                        if (visited.find(caller) == visited.end()) {
-                            queue.push(std::make_pair(caller, depth + 1));
-                            visited.insert(caller);
-                        }
-                    }
-
-                    for (const std::string &callee : callGraph[currentFunc].callees) {
-                        if (visited.find(callee) == visited.end()) {
-                            queue.push(std::make_pair(callee, depth + 1));
-                            visited.insert(callee);
-                        }
-                    }
-                }
-
-                // 更新最大深度
-                for (const auto &pair : depths) {
-                    const std::string &func = pair.first;
-                    unsigned depth = pair.second;
-                    maxCallDepths[func] = std::max(maxCallDepths[func], depth);
-                }
-            }
-        }
-
-        void generateCallGraphs() {
-            LOG_INFO("generateCallGraphs", "Generating complete call graphs");
-
-            // 分别生成目标项目和掩体项目的调用图
-            generateProjectCallGraph("Target Project Call Graph", true);
-            generateProjectCallGraph("Cover Project Call Graph", false);
-        }
-
-        void generateProjectCallGraph(const std::string &title, bool isTarget) {
-            errs() << "```mermaid\n";
-            errs() << "graph TD\n";
-            errs() << "    %% " << title << "\n";
-            
-            // 添加节点
-            for (const auto &pair : callGraph) {
-                const std::string &name = pair.first;
-                const CallNode &node = pair.second;
-                if (node.isTarget == isTarget) {
-                    std::string nodeId = sanitizeNodeId(name);
-                    std::string depth = std::to_string(maxCallDepths[name]);
-                    std::string style = node.isTarget ? ":::target" : "";
-                    
-                    errs() << "    " << nodeId << "[\"" << name 
-                        << "\\nDepth: " << depth << "\"]" << style << "\n";
-                }
-            }
-            
-            // 添加边
-            for (const auto &pair : callGraph) {
-                const std::string &name = pair.first;
-                const CallNode &node = pair.second;
-                if (node.isTarget == isTarget) {
-                    std::string callerId = sanitizeNodeId(name);
-                    
-                    for (const auto &callee : node.callees) {
-                        if (callGraph.at(callee).isTarget == isTarget) {
-                            std::string calleeId = sanitizeNodeId(callee);
-                            errs() << "    " << callerId << " --> " << calleeId << "\n";
-                        }
-                    }
-                }
-            }
-            
-            // 添加样式定义
-            errs() << "    classDef target fill:#f96,stroke:#333,stroke-width:4px\n";
-            errs() << "```\n\n";
-        }
-
-        void findSimilarStructures() {
-            LOG_INFO("findSimilarStructures", "Analyzing call graph similarities");
-
-            // 为每个函数计算特征签名
-            std::map<std::string, FunctionSignature> signatures;
-            for (const auto &pair : callGraph) {
-                const std::string &name = pair.first;
-                const CallNode &node = pair.second;
-                
-                FunctionSignature sig;
-                sig.inDegree = node.callers.size();
-                sig.outDegree = node.callees.size();
-                sig.depth = maxCallDepths[name];
-
-                // 收集调用者深度
-                for (const auto &caller : node.callers) {
-                    sig.callerDepths.push_back(maxCallDepths[caller]);
-                }
-                std::sort(sig.callerDepths.begin(), sig.callerDepths.end());
-
-                // 收集被调用者深度
-                for (const auto &callee : node.callees) {
-                    sig.calleeDepths.push_back(maxCallDepths[callee]);
-                }
-                std::sort(sig.calleeDepths.begin(), sig.calleeDepths.end());
-
-                signatures[name] = sig;
-            }
-
-            // 比较目标函数和掩体函数的相似度
-            for (const auto &targetFunc : targetFunctions) {
-                const auto &targetSig = signatures[targetFunc];
-                std::vector<std::pair<std::string, double>> similarities;
-
-                for (const auto &pair : callGraph) {
-                    const std::string &name = pair.first;
-                    const CallNode &node = pair.second;
-                    
-                    if (!node.isTarget) {
-                        const auto &coverSig = signatures[name];
-                        
-                        // 计算相似度得分
-                        double similarity = calculateSignatureSimilarity(targetSig, coverSig);
-                        
-                        if (similarity > 0.8) { // 相似度阈值
-                            similarities.emplace_back(name, similarity);
-                        }
-                    }
-                }
-
-                // 输出相似函数
-                if (!similarities.empty()) {
-                    LOG_INFO("findSimilarStructures", 
-                        "Similar functions for {0}:", targetFunc);
-                    for (const auto &pair : similarities) {
-                        const std::string &name = pair.first;
-                        double similarity = pair.second;
-                        LOG_INFO("findSimilarStructures", 
-                            "  {0} (similarity: {1:.2f})", name, similarity);
-                    }
-                }
-            }
-        }
-
-        double calculateSignatureSimilarity(
-            const FunctionSignature &sig1, 
-            const FunctionSignature &sig2) {
-            
-            double score = 0.0;
-            unsigned totalFactors = 0;
-
-            // 比较入度和出度
-            if (sig1.inDegree > 0 || sig2.inDegree > 0) {
-                score += 1.0 - std::abs(int(sig1.inDegree) - int(sig2.inDegree)) / 
-                    double(std::max(sig1.inDegree, sig2.inDegree));
-                totalFactors++;
-            }
-            
-            if (sig1.outDegree > 0 || sig2.outDegree > 0) {
-                score += 1.0 - std::abs(int(sig1.outDegree) - int(sig2.outDegree)) / 
-                    double(std::max(sig1.outDegree, sig2.outDegree));
-                totalFactors++;
-            }
-
-            // 比较深度
-            if (sig1.depth > 0 || sig2.depth > 0) {
-                score += 1.0 - std::abs(int(sig1.depth) - int(sig2.depth)) / 
-                    double(std::max(sig1.depth, sig2.depth));
-                totalFactors++;
-            }
-
-            // 比较调用者深度分布
-            if (!sig1.callerDepths.empty() && !sig2.callerDepths.empty()) {
-                score += compareDepthVectors(sig1.callerDepths, sig2.callerDepths);
-                totalFactors++;
-            }
-
-            // 比较被调用者深度分布
-            if (!sig1.calleeDepths.empty() && !sig2.calleeDepths.empty()) {
-                score += compareDepthVectors(sig1.calleeDepths, sig2.calleeDepths);
-                totalFactors++;
-            }
-
-            return totalFactors > 0 ? score / totalFactors : 0.0;
-        }
-
-        double compareDepthVectors(
-            const std::vector<unsigned> &v1, 
-            const std::vector<unsigned> &v2) {
-            
-            size_t maxSize = std::max(v1.size(), v2.size());
-            size_t minSize = std::min(v1.size(), v2.size());
-            
-            // 首先比较向量大小的相似度
-            double sizeSimilarity = double(minSize) / maxSize;
-            
-            // 然后比较实际值的相似度
-            double valueSimilarity = 0.0;
-            for (size_t i = 0; i < minSize; i++) {
-                valueSimilarity += 1.0 - std::abs(int(v1[i]) - int(v2[i])) / 
-                    double(std::max(v1[i], v2[i]));
-            }
-            valueSimilarity /= maxSize;
-
-            return (sizeSimilarity + valueSimilarity) / 2.0;
-        }
-
-        std::string sanitizeNodeId(const std::string &name) {
-            std::string id = name;
-            std::replace(id.begin(), id.end(), '.', '_');
-            std::replace(id.begin(), id.end(), ' ', '_');
-            std::replace(id.begin(), id.end(), '-', '_');
-            return id;
-        }
-
-        bool isTargetCode(Function &F) {
-            if (MDNode *MD = F.getMetadata("project_source")) {
-                if (MDString *ProjectStr = dyn_cast<MDString>(MD->getOperand(0))) {
-                    std::string projectName = ProjectStr->getString().str();
-                    return (projectName == "Target");
-                }
-            }
-            return false;
-        }
-    };
-}
-
-char CodeFusionPass::ID = 0;
-static RegisterPass<CodeFusionPass> X("codefusion", "Code Fusion Pass");

+ 1028 - 0
src/Fusion/Fusion.cpp

@@ -0,0 +1,1028 @@
+#include <algorithm>
+
+#include "../Util/LogSystem.h"
+#include "../Util/Utils.h"
+
+#include "Fusion.h"
+
+
+using namespace llvm;
+using namespace slicefusion;
+
+extern logging::LogSystem logger;
+
+/**
+ * @brief 生成一个伪随机索引
+ * 
+ * @param max 生成的随机数的上限值
+ * @return size_t 返回一个[0, max)范围内的随机索引
+ * 
+ * 使用线性同余法(LCG)生成伪随机数:
+ * - 乘数 a = 1103515245
+ * - 增量 c = 12345
+ * - 模数 m = 0x7fffffff
+ * 该函数用于在函数匹配过程中随机选择掩护函数
+ */
+size_t Fusion::getRandomIndex(size_t max) {
+    static unsigned seed = 0;
+    seed = (seed * 1103515245 + 12345) & 0x7fffffff;
+    return seed % max;
+}
+
+/**
+ * @brief 为目标函数匹配合适的掩护函数
+ * 
+ * @param targetFunctions 需要被保护的目标函数集合
+ * @param bunkerFunctions 可用作掩护的函数集合
+ * @return bool 如果所有目标函数都成功匹配到掩护函数则返回true,否则返回false
+ * 
+ * 匹配过程:
+ * 1. 首先检查掩护函数数量是否足够
+ * 2. 将目标函数按照代码切片数量降序排序
+ * 3. 对每个目标函数:
+ *    - 随机选择一个掩护函数
+ *    - 检查掩护函数的融合点是否足够
+ *    - 如果合适则建立匹配,否则继续尝试其他掩护函数
+ * 
+ * 匹配原则:
+ * - 掩护函数的融合点数量必须大于等于目标函数的代码切片数量
+ * - 每个掩护函数只能匹配一个目标函数
+ * - 优先处理切片数量多的目标函数
+ */
+bool Fusion::matchFunctionsForFusion(
+    const std::set<std::string>& targetFunctions,
+    const std::set<std::string>& bunkerFunctions) {
+    auto& logger = logging::LogSystem::getInstance();
+    logger.enableFunction("matchFunctionsForFusion");
+    LOG_INFO("matchFunctionsForFusion", "Starting function matching process");
+    // 检查掩护函数数量是否足够
+    if (bunkerFunctions.size() < targetFunctions.size()) {
+        LOG_WARNING("matchFunctionsForFusion", 
+            "Insufficient bunker functions ({0}) for target functions ({1})", 
+            bunkerFunctions.size(), 
+            targetFunctions.size());
+        return false;
+    }
+    // 将目标函数按照切片数量降序排序
+    std::vector<std::string> sortedTargets(targetFunctions.begin(), targetFunctions.end());
+    std::sort(sortedTargets.begin(), sortedTargets.end(),
+        [this](const std::string& a, const std::string& b) {
+            return callGraph[a].slices_num > callGraph[b].slices_num;  // 降序排列
+        });
+    // 创建可用掩护函数列表
+    std::vector<std::string> availableBunkers(bunkerFunctions.begin(), bunkerFunctions.end());
+    // 为每个目标函数寻找匹配的掩护函数
+    for (const auto& targetFunc : sortedTargets) {
+        const auto& targetNode = callGraph[targetFunc];
+        size_t requiredPoints = targetNode.slices_num;
+
+        bool matched = false;
+        while (!availableBunkers.empty() && !matched) {
+            // 随机选择一个掩护函数
+            size_t idx = getRandomIndex(availableBunkers.size());
+            const auto& bunkerFunc = availableBunkers[idx];
+            const auto& bunkerNode = callGraph[bunkerFunc];
+            // 检查掩护函数的融合点是否足够
+            if (bunkerNode.points_num >= requiredPoints) {
+                // 建立匹配关系
+                fusionPairs[targetFunc] = bunkerFunc;
+                availableBunkers.erase(availableBunkers.begin() + idx);
+                matched = true;
+                LOG_INFO("matchFunctionsForFusion", 
+                    "Matched target {0} ({1} slices) with bunker {2} ({3} fusion points)",
+                    targetFunc, 
+                    targetNode.slices_num,
+                    bunkerFunc,
+                    bunkerNode.points_num);
+            } else {
+                // 移除不合适的掩护函数
+                availableBunkers.erase(availableBunkers.begin() + idx);
+            }
+        }
+        // 如果没有找到合适的掩护函数,返回失败
+        if (!matched) {
+            LOG_ERROR("matchFunctionsForFusion", 
+                "Could not find suitable bunker function for target {0}", 
+                targetFunc);
+            return false;
+        }
+    }
+    return true;
+}
+
+/**
+ * @brief 执行代码融合操作,将目标函数与掩护函数融合为新的函数
+ * 
+ * @param M LLVM模块,包含所有需要处理的函数
+ * 
+ */
+void Fusion::performCodeFusion(Module &M) {
+    auto& logger = logging::LogSystem::getInstance();
+    logger.enableFunction("performCodeFusion");
+    LOG_INFO("performCodeFusion", "Starting code fusion");
+    
+    // 打印所有fusion pairs
+    LOG_INFO("performCodeFusion", "Total fusion pairs: {0}", fusionPairs.size());
+    for (const auto& pair : fusionPairs) {
+        LOG_INFO("performCodeFusion", "Fusion pair: target={0}, bunker={1}", 
+            pair.first, pair.second);
+    }
+
+    // 遍历所有需要融合的函数对
+    for (const auto& fusion : fusionPairs) {
+        const std::string& targetName = fusion.first;
+        const std::string& bunkerName = fusion.second;
+        // 获取目标函数和掩护函数
+        Function* targetFunc = M.getFunction(targetName);
+        Function* bunkerFunc = M.getFunction(bunkerName);
+        if (!targetFunc || !bunkerFunc) {
+            LOG_ERROR("performCodeFusion", 
+                "Cannot find functions: target={0}, bunker={1}", 
+                targetName, bunkerName);
+            continue;
+        }
+        LOG_INFO("performCodeFusion", 
+            "Processing function pair: target={0}, bunker={1}", 
+            targetName, bunkerName);
+        // 1. 创建融合函数
+        FunctionType* fusedType = createFusedFunctionType(bunkerFunc, targetFunc, M.getContext());
+        Function* fusedFunc = Function::Create(fusedType, bunkerFunc->getLinkage(),
+            "fused_" + bunkerName, &M);
+        // 创建入口基本块
+        BasicBlock* entryBlock = BasicBlock::Create(M.getContext(), "entry", fusedFunc);
+        IRBuilder<> Builder(entryBlock);
+    
+        // 2. 设置参数映射
+        Value* isTarget = fusedFunc->arg_begin();  // 控制参数
+        ValueToValueMapTy bunkerVMap, targetVMap;
+        unsigned argIdx = 1; // 跳过isTarget参数
+        
+        // 在克隆基本块之前,先处理所有的alloca指令
+        IRBuilder<> AllocaBuilder(entryBlock);
+        // 收集需要删除的alloca指令和它们的映射
+        std::map<AllocaInst*, AllocaInst*> bunkerAllocaReplacements;
+        std::map<AllocaInst*, AllocaInst*> targetAllocaReplacements;
+        // 处理bunker函数的alloca并移动到entry块
+        for (auto& BB : *bunkerFunc) {
+            for (auto& I : BB) {
+                if (AllocaInst* AI = dyn_cast<AllocaInst>(&I)) {
+                    // 在entry块创建新的alloca,保持原始名称
+                    AllocaInst* NewAI = AllocaBuilder.CreateAlloca(
+                        AI->getAllocatedType(),
+                        AI->getArraySize(),
+                        AI->getName());
+                    // 保存新旧alloca的映射关系
+                    bunkerAllocaReplacements[AI] = NewAI;
+                }
+            }
+        }
+        // 处理target函数的alloca并移动到entry块
+        for (auto& BB : *targetFunc) {
+            for (auto& I : BB) {
+                if (AllocaInst* AI = dyn_cast<AllocaInst>(&I)) {
+                    // 在entry块创建新的alloca,保持原始名称
+                    AllocaInst* NewAI = AllocaBuilder.CreateAlloca(
+                        AI->getAllocatedType(),
+                        AI->getArraySize(),
+                        AI->getName());
+                    // 保存新旧alloca的映射关系
+                    targetAllocaReplacements[AI] = NewAI;
+                }
+            }
+        }
+        // 更新VMap,确保使用正确的alloca映射
+        for (auto& Pair : bunkerAllocaReplacements) {
+            bunkerVMap[Pair.first] = Pair.second;
+            Pair.first->replaceAllUsesWith(Pair.second);
+            Pair.first->eraseFromParent();
+        }
+        for (auto& Pair : targetAllocaReplacements) {
+            targetVMap[Pair.first] = Pair.second;
+            Pair.first->replaceAllUsesWith(Pair.second);
+            Pair.first->eraseFromParent();
+        }
+        // 映射bunker函数参数
+        for (auto& arg : bunkerFunc->args()) {
+            bunkerVMap[&arg] = fusedFunc->getArg(argIdx++);
+        }
+        // 映射target函数参数
+        for (auto& arg : targetFunc->args()) {
+            targetVMap[&arg] = fusedFunc->getArg(argIdx++);
+        }
+
+        // 3. 准备融合所需的数据结构
+        const auto& targetSlices = callGraph[targetName].slices;
+        const auto& criticalPoints = callGraph[bunkerName].criticalPoints;
+        const auto& isPredValid = callGraph[bunkerName].isPredValid;
+        const auto& isSuccValid = callGraph[bunkerName].isSuccValid;
+        size_t currentSliceIndex = 0;
+        // 用于存储克隆的基本块映射关系
+        std::map<BasicBlock*, BasicBlock*> originToCloneBunkerBlockMap;
+        std::map<BasicBlock*, BasicBlock*> originToCloneTargetBlockMap;
+        std::map<BasicBlock*, BasicBlock*> cloneToOriginTargetBlockMap;
+        std::map<BasicBlock*, BasicBlock*> cloneToOriginBunkerBlockMap;
+        std::vector<BasicBlock*> allFusedBlocks;
+        // 记录已经修改过跳转的块
+        std::set<BasicBlock*> modifiedBranchBlocks;
+        
+        // 4. 克隆和融合基本块
+        BasicBlock* lastBunkerOfPrevSlice = nullptr;
+        BasicBlock* lastBunkerSlicePhiBlock = nullptr;
+
+        for (BasicBlock& BB : *bunkerFunc) {
+            BasicBlock* currentBunkerBB = nullptr;
+            if (currentSliceIndex < targetSlices.size() && criticalPoints.count(&BB)) {
+                auto predIt = isPredValid.find(&BB);
+                auto succIt = isSuccValid.find(&BB);
+                
+                if (predIt != isPredValid.end() && predIt->second) {
+                    // 创建target分片的条件包裹块
+                    BasicBlock* targetCondBB = BasicBlock::Create(M.getContext(), 
+                        "target_cond_" + std::to_string(currentSliceIndex), fusedFunc);
+                    BasicBlock* targetSkipBB = BasicBlock::Create(M.getContext(), 
+                        "target_skip_" + std::to_string(currentSliceIndex), fusedFunc);
+                    BasicBlock* targetPhiBB = BasicBlock::Create(M.getContext(), 
+                        "target_phi_" + std::to_string(currentSliceIndex), fusedFunc);
+                    allFusedBlocks.push_back(targetCondBB);
+                    allFusedBlocks.push_back(targetSkipBB);
+                    // 克隆target块
+                    BasicBlock* firstTargetBB = nullptr;
+                    BasicBlock* lastTargetBB = nullptr;
+                    for (BasicBlock* targetBB : targetSlices[currentSliceIndex].blocks) {
+                        BasicBlock* clonedTargetBB = CloneBasicBlock(targetBB, targetVMap, 
+                            "target_" + targetBB->getName(), fusedFunc);
+                        if (!firstTargetBB) firstTargetBB = clonedTargetBB;
+                        lastTargetBB = clonedTargetBB;
+                        cloneToOriginTargetBlockMap[clonedTargetBB] = targetBB;
+                        originToCloneTargetBlockMap[targetBB] = clonedTargetBB;
+                        allFusedBlocks.push_back(clonedTargetBB);
+                    }
+                    allFusedBlocks.push_back(targetPhiBB);
+                    // 创建条件跳转
+                    // 如果前驱有效,说明上一个bunker分片结束
+                    if (lastBunkerOfPrevSlice && lastBunkerSlicePhiBlock) {
+                        // 创建上一个bunker分片到其phi块的跳转
+                        // 检查lastBunkerOfPrevSlice的终结指令是否为ret
+                        if (!isa<ReturnInst>(lastBunkerOfPrevSlice->getTerminator())) {
+                            lastBunkerOfPrevSlice->getTerminator()->eraseFromParent();
+                            BranchInst::Create(lastBunkerSlicePhiBlock, lastBunkerOfPrevSlice);
+                            modifiedBranchBlocks.insert(lastBunkerOfPrevSlice);
+                        }
+                        BranchInst::Create(targetCondBB, lastBunkerSlicePhiBlock);
+                        modifiedBranchBlocks.insert(lastBunkerSlicePhiBlock);
+                        allFusedBlocks.push_back(lastBunkerOfPrevSlice);
+                        allFusedBlocks.push_back(lastBunkerSlicePhiBlock);
+                    }
+                    BranchInst::Create(firstTargetBB, targetSkipBB, isTarget, targetCondBB);
+                    BranchInst::Create(targetPhiBB, targetSkipBB);
+                    // 检查lastTargetBB的终结指令是否为ret
+                    if (!isa<ReturnInst>(lastTargetBB->getTerminator())) {
+                        lastTargetBB->getTerminator()->eraseFromParent();
+                        BranchInst::Create(targetPhiBB, lastTargetBB);
+                        modifiedBranchBlocks.insert(lastTargetBB);
+                    }
+                    modifiedBranchBlocks.insert(targetCondBB);
+                    modifiedBranchBlocks.insert(targetSkipBB);
+
+                    // 创建bunker块的条件包裹块
+                    BasicBlock* bunkerCondBB = BasicBlock::Create(M.getContext(), 
+                        "bunker_cond_" + std::to_string(currentSliceIndex), fusedFunc);
+                    BasicBlock* bunkerSkipBB = BasicBlock::Create(M.getContext(), 
+                        "bunker_skip_" + std::to_string(currentSliceIndex), fusedFunc);
+                    BasicBlock* bunkerPhiBB = BasicBlock::Create(M.getContext(), 
+                        "bunker_phi_" + std::to_string(currentSliceIndex), fusedFunc);
+                    allFusedBlocks.push_back(bunkerCondBB);
+                    allFusedBlocks.push_back(bunkerSkipBB);
+                    // 克隆bunker块
+                    currentBunkerBB = CloneBasicBlock(&BB, bunkerVMap, 
+                        "bunker_" + BB.getName(), fusedFunc);
+                    cloneToOriginBunkerBlockMap[currentBunkerBB] = &BB;
+                    originToCloneBunkerBlockMap[&BB] = currentBunkerBB;
+                    allFusedBlocks.push_back(currentBunkerBB);
+
+                    // 创建跳转
+                    BranchInst::Create(bunkerCondBB, targetPhiBB);
+                    BranchInst::Create(currentBunkerBB, bunkerSkipBB, 
+                        Builder.CreateNot(isTarget), bunkerCondBB);
+                    BranchInst::Create(bunkerPhiBB, bunkerSkipBB);
+                    modifiedBranchBlocks.insert(bunkerCondBB);
+                    modifiedBranchBlocks.insert(bunkerSkipBB);
+                    modifiedBranchBlocks.insert(targetPhiBB);
+
+                    lastBunkerOfPrevSlice = currentBunkerBB;
+                    lastBunkerSlicePhiBlock = bunkerPhiBB;
+                    currentSliceIndex++;
+
+                } else if (succIt != isSuccValid.end() && succIt->second) {
+                    // 克隆当前bunker块
+                    currentBunkerBB = CloneBasicBlock(&BB, bunkerVMap, 
+                        "bunker_" + BB.getName(), fusedFunc);
+                    cloneToOriginBunkerBlockMap[currentBunkerBB] = &BB;
+                    originToCloneBunkerBlockMap[&BB] = currentBunkerBB;
+                    allFusedBlocks.push_back(currentBunkerBB);
+                    lastBunkerOfPrevSlice = currentBunkerBB;
+                    if (lastBunkerSlicePhiBlock) {
+                        allFusedBlocks.push_back(lastBunkerSlicePhiBlock);
+                    }
+                    // 创建target分片的条件包裹块
+                    BasicBlock* targetCondBB = BasicBlock::Create(M.getContext(), 
+                        "target_cond_" + std::to_string(currentSliceIndex), fusedFunc);
+                    BasicBlock* targetSkipBB = BasicBlock::Create(M.getContext(), 
+                        "target_skip_" + std::to_string(currentSliceIndex), fusedFunc);
+                    BasicBlock* targetPhiBB = BasicBlock::Create(M.getContext(), 
+                        "target_phi_" + std::to_string(currentSliceIndex), fusedFunc);
+                    allFusedBlocks.push_back(targetCondBB);
+                    allFusedBlocks.push_back(targetSkipBB);
+                    // 克隆target块
+                    BasicBlock* firstTargetBB = nullptr;
+                    BasicBlock* lastTargetBB = nullptr;
+                    for (BasicBlock* targetBB : targetSlices[currentSliceIndex].blocks) {
+                        BasicBlock* clonedTargetBB = CloneBasicBlock(targetBB, targetVMap, 
+                            "target_" + targetBB->getName(), fusedFunc);
+                        if (!firstTargetBB) firstTargetBB = clonedTargetBB;
+                        lastTargetBB = clonedTargetBB;
+                        cloneToOriginTargetBlockMap[clonedTargetBB] = targetBB;
+                        originToCloneTargetBlockMap[targetBB] = clonedTargetBB;
+                        allFusedBlocks.push_back(clonedTargetBB);
+                    }
+                    allFusedBlocks.push_back(targetPhiBB);
+                    // 创建跳转
+                    // 如果后继有效,处理上一个bunker分片
+                    if (lastBunkerOfPrevSlice && lastBunkerSlicePhiBlock) {
+                        // 创建上一个bunker分片到其phi块的跳转
+                        // 检查lastBunkerOfPrevSlice的终结指令是否为ret
+                        if (!isa<ReturnInst>(lastBunkerOfPrevSlice->getTerminator())) {
+                            lastBunkerOfPrevSlice->getTerminator()->eraseFromParent();
+                            BranchInst::Create(lastBunkerSlicePhiBlock, lastBunkerOfPrevSlice);
+                            modifiedBranchBlocks.insert(lastBunkerOfPrevSlice);
+                        }
+                        BranchInst::Create(targetCondBB, lastBunkerSlicePhiBlock);
+                        modifiedBranchBlocks.insert(lastBunkerSlicePhiBlock);
+                    }
+                    BranchInst::Create(firstTargetBB, targetSkipBB, isTarget, targetCondBB);
+                    BranchInst::Create(targetPhiBB, targetSkipBB);
+                    // 检查lastTargetBB的终结指令是否为ret
+                    if (!isa<ReturnInst>(lastTargetBB->getTerminator())) {
+                        lastTargetBB->getTerminator()->eraseFromParent();
+                        BranchInst::Create(targetPhiBB, lastTargetBB);
+                        modifiedBranchBlocks.insert(lastTargetBB);
+                    }
+                    modifiedBranchBlocks.insert(targetCondBB);
+                    modifiedBranchBlocks.insert(targetSkipBB);
+
+                    lastBunkerOfPrevSlice = nullptr;
+                    lastBunkerSlicePhiBlock = nullptr;
+                    currentSliceIndex++;
+                } else {
+                    LOG_WARNING("performCodeFusion", 
+                        "Critical point found but neither pred nor succ is valid in block: {0}", 
+                        BB.getName().str());
+                }
+            } else {
+                // 克隆普通bunker基本块
+                currentBunkerBB = CloneBasicBlock(&BB, bunkerVMap, 
+                    "bunker_" + BB.getName(), fusedFunc);
+                cloneToOriginBunkerBlockMap[currentBunkerBB] = &BB;
+                originToCloneBunkerBlockMap[&BB] = currentBunkerBB;
+                allFusedBlocks.push_back(currentBunkerBB);
+                lastBunkerOfPrevSlice = currentBunkerBB;
+            }
+        }
+        // 添加从entry块到第一个条件块的跳转
+        if (!allFusedBlocks.empty()) {
+            BasicBlock* entryBlock = &fusedFunc->getEntryBlock();
+            BasicBlock* firstBlock = allFusedBlocks.front();
+            BranchInst::Create(firstBlock, entryBlock);
+            modifiedBranchBlocks.insert(entryBlock);
+        }
+
+        LOG_INFO("performCodeFusion", "[After clone]Generated control flow graph for fused function:");
+        callGraph.dumpControlFlowGraph(*fusedFunc);
+
+        // 5. 修复基本块间的跳转关系
+        for (BasicBlock* BB : allFusedBlocks) {
+            // 修复所有非终结指令
+            for (Instruction &I : make_range(BB->begin(), --BB->end())) {
+                if (cloneToOriginTargetBlockMap.count(BB)) {
+                    RemapInstruction(&I, targetVMap, RF_NoModuleLevelChanges);
+                } else {
+                    RemapInstruction(&I, bunkerVMap, RF_NoModuleLevelChanges);
+                }
+            }
+            // 如果已经修改过跳转,则跳过
+            if (modifiedBranchBlocks.count(BB)) {
+                continue;
+            }
+            // 如果没有终结指令,暂时跳过
+            Instruction* terminator = BB->getTerminator();
+            if (!terminator) {
+                LOG_WARNING("performCodeFusion", "No terminator found in block: {0}", BB->getName().str());
+                continue;
+            }
+            // 修复终结指令(跳转指令和返回指令)
+            if (BranchInst* BI = dyn_cast<BranchInst>(terminator)) {
+                // 先修复条件跳转指令本身
+                if (cloneToOriginTargetBlockMap.count(BB)) {
+                    RemapInstruction(BI, targetVMap, RF_NoModuleLevelChanges);
+                } else {
+                    RemapInstruction(BI, bunkerVMap, RF_NoModuleLevelChanges);
+                }
+                // 然后修复跳转目标
+                if (cloneToOriginTargetBlockMap.count(BB)) {
+                    // 修复target块的跳转
+                    BasicBlock* origBB = cloneToOriginTargetBlockMap[BB];
+                    BranchInst* origBI = cast<BranchInst>(origBB->getTerminator());
+                    for (unsigned i = 0; i < origBI->getNumSuccessors(); i++) {
+                        BasicBlock* origSucc = origBI->getSuccessor(i);
+                        if (originToCloneTargetBlockMap.count(origSucc)) {
+                            BasicBlock* cloneSucc = originToCloneTargetBlockMap[origSucc];
+                            BI->setSuccessor(i, cloneSucc);
+                        }
+                    }
+                } else {
+                    // 修复bunker块的跳转
+                    BasicBlock* origBB = cloneToOriginBunkerBlockMap[BB];
+                    BranchInst* origBI = cast<BranchInst>(origBB->getTerminator());
+                    for (unsigned i = 0; i < origBI->getNumSuccessors(); i++) {
+                        BasicBlock* origSucc = origBI->getSuccessor(i);
+                        if (originToCloneBunkerBlockMap.count(origSucc)) {
+                            BasicBlock* cloneSucc = originToCloneBunkerBlockMap[origSucc];
+                            BI->setSuccessor(i, cloneSucc);
+                        }
+                    }
+                }
+            } else if (ReturnInst* RI = dyn_cast<ReturnInst>(terminator)) {
+                // 修复返回指令
+                LOG_INFO("performCodeFusion", "Fixing return instruction in block {0}", getNodeId(BB));
+                if (cloneToOriginTargetBlockMap.count(BB)) {
+                    RemapInstruction(RI, targetVMap, RF_NoModuleLevelChanges);
+                } else {
+                    RemapInstruction(RI, bunkerVMap, RF_NoModuleLevelChanges);
+                }
+            }
+        }
+
+        LOG_INFO("performCodeFusion", "[After fix]Generated control flow graph for fused function:");
+        callGraph.dumpControlFlowGraph(*fusedFunc);
+
+        // 6. 处理返回值
+        Type* returnType = fusedFunc->getReturnType();
+        if (!returnType->isVoidTy()) {
+            if (StructType* STy = dyn_cast<StructType>(returnType)) {
+                // 处理结构体返回类型
+                LOG_INFO("performCodeFusion", "Processing struct return type");
+                for (auto& pair : cloneToOriginBunkerBlockMap) {
+                    BasicBlock* BB = pair.first;
+                    for (auto I = BB->begin(); I != BB->end(); ) {
+                        if (ReturnInst* RI = dyn_cast<ReturnInst>(&*I)) {
+                            IRBuilder<> RetBuilder(RI);
+                            Value* bunkerRetVal = RI->getReturnValue();
+                            Value* structVal = UndefValue::get(STy);
+                            // 设置结构体字段
+                            structVal = RetBuilder.CreateInsertValue(structVal, 
+                                Constant::getNullValue(STy->getElementType(0)), 0);
+                            structVal = RetBuilder.CreateInsertValue(structVal, bunkerRetVal, 1);
+                            ReturnInst* newRI = ReturnInst::Create(M.getContext(), structVal);
+                            newRI->insertBefore(RI);
+                            RI->eraseFromParent();
+                            break;
+                        }
+                        ++I;
+                    }
+                }
+                for (auto& pair : cloneToOriginTargetBlockMap) {
+                    BasicBlock* BB = pair.first;
+                    for (auto I = BB->begin(); I != BB->end(); ) {
+                        if (ReturnInst* RI = dyn_cast<ReturnInst>(&*I)) {
+                            IRBuilder<> RetBuilder(RI);
+                            Value* targetRetVal = RI->getReturnValue();
+                            Value* structVal = UndefValue::get(STy);
+                            // 设置结构体字段
+                            structVal = RetBuilder.CreateInsertValue(structVal, targetRetVal, 0);
+                            structVal = RetBuilder.CreateInsertValue(structVal, 
+                                Constant::getNullValue(STy->getElementType(1)), 1);
+                            ReturnInst* newRI = ReturnInst::Create(M.getContext(), structVal);
+                            newRI->insertBefore(RI);
+                            RI->eraseFromParent();
+                            break;
+                        }
+                        ++I;
+                    }
+                }
+            } else {
+                // 处理非结构体的返回类型
+                LOG_INFO("performCodeFusion", "Processing non-struct return type: {0}", 
+                    getReadableTypeName(returnType));
+                // 处理bunker块的返回值
+                for (auto& pair : cloneToOriginBunkerBlockMap) {
+                    BasicBlock* BB = pair.first;
+                    LOG_INFO("performCodeFusion", "Processing bunker block: {0}", getNodeId(BB));
+                    for (auto I = BB->begin(); I != BB->end(); ) {
+                        if (ReturnInst* RI = dyn_cast<ReturnInst>(&*I)) {
+                            Value* bunkerRetVal = RI->getReturnValue();
+                            bool needsModification = false;
+                            if (bunkerRetVal) {
+                                LOG_INFO("performCodeFusion", "Found return instruction in bunker block {0}. Return value type: {1}", 
+                                    getNodeId(BB),
+                                    getReadableTypeName(bunkerRetVal->getType()));
+                                needsModification = (bunkerRetVal->getType() != returnType);
+                            } else {
+                                LOG_INFO("performCodeFusion", "Found void return instruction in bunker block {0}", 
+                                    getNodeId(BB));
+                                needsModification = !returnType->isVoidTy();
+                            }
+                            if (needsModification) {
+                                LOG_INFO("performCodeFusion", 
+                                    "Return type mismatch in bunker block {0}. Expected: {1}, Found: {2}",
+                                    getNodeId(BB),
+                                    getReadableTypeName(returnType),
+                                    bunkerRetVal ? getReadableTypeName(bunkerRetVal->getType()) : "void");
+                                
+                                IRBuilder<> RetBuilder(RI);
+                                Value* defaultVal = nullptr;
+                                if (!returnType->isVoidTy()) {
+                                    defaultVal = Constant::getNullValue(returnType);
+                                }
+                                ReturnInst* newRI = defaultVal ? 
+                                    ReturnInst::Create(M.getContext(), defaultVal) :
+                                    ReturnInst::Create(M.getContext());
+                                newRI->insertBefore(RI);
+                                RI->eraseFromParent();
+                                LOG_INFO("performCodeFusion", "Created new return instruction with {0} in block {1}", 
+                                    returnType->isVoidTy() ? "void" : "default value",
+                                    getNodeId(BB));
+                            }
+                            break;
+                        }
+                        ++I;
+                    }
+                }
+                
+                // 处理target块的返回值
+                for (auto& pair : cloneToOriginTargetBlockMap) {
+                    BasicBlock* BB = pair.first;
+                    LOG_INFO("performCodeFusion", "Processing target block: {0}", getNodeId(BB));
+                    for (auto I = BB->begin(); I != BB->end(); ) {
+                        if (ReturnInst* RI = dyn_cast<ReturnInst>(&*I)) {
+                            Value* targetRetVal = RI->getReturnValue();
+                            bool needsModification = false;
+                            if (targetRetVal) {
+                                LOG_INFO("performCodeFusion", "Found return instruction in target block {0}. Return value type: {1}", 
+                                    getNodeId(BB),
+                                    getReadableTypeName(targetRetVal->getType()));
+                                needsModification = (targetRetVal->getType() != returnType);
+                            } else {
+                                LOG_INFO("performCodeFusion", "Found void return instruction in target block {0}", 
+                                    getNodeId(BB));
+                                needsModification = !returnType->isVoidTy();
+                            }
+                            if (needsModification) {
+                                LOG_INFO("performCodeFusion", 
+                                    "Return type mismatch in target block {0}. Expected: {1}, Found: {2}",
+                                    getNodeId(BB),
+                                    getReadableTypeName(returnType),
+                                    targetRetVal ? getReadableTypeName(targetRetVal->getType()) : "void");
+                                IRBuilder<> RetBuilder(RI);
+                                Value* defaultVal = nullptr;
+                                if (!returnType->isVoidTy()) {
+                                    defaultVal = Constant::getNullValue(returnType);
+                                }
+                                ReturnInst* newRI = defaultVal ? 
+                                    ReturnInst::Create(M.getContext(), defaultVal) :
+                                    ReturnInst::Create(M.getContext());
+                                newRI->insertBefore(RI);
+                                RI->eraseFromParent();
+                                LOG_INFO("performCodeFusion", "Created new return instruction with {0} in block {1}", 
+                                    returnType->isVoidTy() ? "void" : "default value",
+                                    getNodeId(BB));
+                            }
+                            break;
+                        }
+                        ++I;
+                    }
+                }
+            }
+        }
+        LOG_INFO("performCodeFusion", "[After fix return]Generated control flow graph for fused function:");
+        callGraph.dumpControlFlowGraph(*fusedFunc);
+
+        // 7. 更新调用点
+        std::vector<CallInst*> bunkerCalls;
+        std::vector<CallInst*> targetCalls;
+        for (auto& U : bunkerFunc->uses()) {
+            if (CallInst* CI = dyn_cast<CallInst>(U.getUser())) {
+                bunkerCalls.push_back(CI);
+            }
+        }
+        for (auto& U : targetFunc->uses()) {
+            if (CallInst* CI = dyn_cast<CallInst>(U.getUser())) {
+                targetCalls.push_back(CI);
+            }
+        }
+        for (CallInst* CI : bunkerCalls) {
+            updateCallSite(CI, fusedFunc, bunkerFunc, targetFunc, false);
+        }
+        for (CallInst* CI : targetCalls) {
+            updateCallSite(CI, fusedFunc, targetFunc, bunkerFunc, true);
+        }
+        LOG_INFO("performCodeFusion", "[After update call site]Generated control flow graph for fused function:");
+        callGraph.dumpControlFlowGraph(*fusedFunc);
+
+        // 8 修复缺少终结指令的基本块
+        LOG_INFO("performCodeFusion", "Fixing blocks without terminators...");
+        for (BasicBlock& BB : *fusedFunc) {
+            if (!BB.getTerminator()) {
+                IRBuilder<> Builder(&BB);
+                if (fusedFunc->getReturnType()->isVoidTy()) {
+                    // void返回类型,直接添加ret void
+                    Builder.CreateRetVoid();
+                    LOG_INFO("performCodeFusion", "Added void return to block: {0}", BB.getName().str());
+                } else {
+                    // 非void返回类型,添加带默认值的return
+                    Value* defaultVal = nullptr;
+                    if (StructType* STy = dyn_cast<StructType>(fusedFunc->getReturnType())) {
+                        // 结构体返回类型
+                        Value* structVal = UndefValue::get(STy);
+                        // 设置结构体字段为默认值
+                        structVal = Builder.CreateInsertValue(structVal, 
+                            Constant::getNullValue(STy->getElementType(0)), 0);
+                        structVal = Builder.CreateInsertValue(structVal, 
+                            Constant::getNullValue(STy->getElementType(1)), 1);
+                        defaultVal = structVal;
+                    } else {
+                        // 非结构体返回类型
+                        defaultVal = Constant::getNullValue(fusedFunc->getReturnType());
+                    }
+                    Builder.CreateRet(defaultVal);
+                    LOG_INFO("performCodeFusion", 
+                        "Added return with default value to block: {0}", 
+                        BB.getName().str());
+                }
+            }
+        }
+
+        // 9. 修复PHI节点
+        LOG_INFO("performCodeFusion", "Starting PHI node repair");
+        for (BasicBlock* BB : allFusedBlocks) {
+            for (PHINode& Phi : BB->phis()) {
+                std::vector<std::pair<Value*, BasicBlock*>> incomingVals;
+                // 收集所有输入
+                for (unsigned i = 0; i < Phi.getNumIncomingValues(); i++) {
+                    incomingVals.push_back(std::make_pair(
+                        Phi.getIncomingValue(i),
+                        Phi.getIncomingBlock(i)
+                    ));
+                }
+                // 移除所有旧的输入
+                while (Phi.getNumIncomingValues() > 0) {
+                    Phi.removeIncomingValue((unsigned)0, false);
+                }
+                // 添加新的输入,使用正确的映射关系
+                for (const auto& incomingPair : incomingVals) {
+                    Value* Val = incomingPair.first;
+                    BasicBlock* PredBB = incomingPair.second;
+                    BasicBlock* newPred = nullptr;
+                    // 检查是否是target函数的基本块
+                    if (originToCloneTargetBlockMap.count(PredBB)) {
+                        newPred = originToCloneTargetBlockMap[PredBB];
+                        if (Value* mappedVal = targetVMap[Val]) {
+                            Val = mappedVal;
+                        }
+                    }
+                    // 检查是否是bunker函数的基本块
+                    else if (originToCloneBunkerBlockMap.count(PredBB)) {
+                        newPred = originToCloneBunkerBlockMap[PredBB];
+                        if (Value* mappedVal = bunkerVMap[Val]) {
+                            Val = mappedVal;
+                        }
+                    }
+                    // 检查是否是新创建的条件块或跳转块
+                    else {
+                        newPred = PredBB;
+                    }
+                    if (newPred) {
+                        LOG_DEBUG("performCodeFusion", 
+                            "Updating PHI node in {0}: mapped predecessor {1} to {2}",
+                            getNodeId(BB),
+                            getNodeId(PredBB),
+                            getNodeId(newPred));
+                        Phi.addIncoming(Val, newPred);
+                    }
+                }
+            }
+        }
+        LOG_INFO("performCodeFusion", "[After fix PHI]Generated control flow graph for fused function:");
+        callGraph.dumpControlFlowGraph(*fusedFunc);
+
+        // 10. 删除原始函数
+        LOG_INFO("performCodeFusion", "Attempting to delete original functions...");
+        bunkerFunc->eraseFromParent();
+        targetFunc->eraseFromParent();
+        LOG_INFO("performCodeFusion", "[After erase]Generated control flow graph for fused function:");
+        callGraph.dumpControlFlowGraph(*fusedFunc);
+
+        LOG_INFO("performCodeFusion", 
+            "Completed function fusion: {0}", 
+            fusedFunc->getName().str());
+    }
+    
+    LOG_INFO("performCodeFusion", 
+        "Code fusion completed, processed {0} function pairs", 
+        fusionPairs.size());
+}
+
+/**
+ * @brief 创建融合函数的类型
+ * @param bunkerFunc 掩护函数指针
+ * @param targetFunc 目标函数指针
+ * @param Context LLVM上下文
+ * @return 融合后的函数类型
+ * 
+ * 该函数负责创建融合函数的函数类型,包括:
+ * 1. 添加控制参数(bool类型)用于区分目标函数和掩护函数的执行路径
+ * 2. 合并两个函数的参数列表
+ * 3. 根据两个函数的返回类型创建融合后的返回类型:
+ *    - 如果都是void类型,则返回void
+ *    - 如果其中一个是void,使用另一个的返回类型
+ *    - 如果都不是void,创建包含两个返回值的结构体类型
+ */
+FunctionType* Fusion::createFusedFunctionType(Function* bunkerFunc, Function* targetFunc, LLVMContext& Context) {
+    auto& logger = logging::LogSystem::getInstance();
+    // logger.enableFunction("createFusedFunctionType");
+    LOG_DEBUG("createFusedFunctionType", 
+        "Creating fused type for bunker={0}({1}) and target={2}({3})", 
+        bunkerFunc->getName().str(),
+        getReadableTypeName(bunkerFunc->getReturnType()),
+        targetFunc->getName().str(),
+        getReadableTypeName(targetFunc->getReturnType()));
+    std::vector<Type*> paramTypes;
+    // 添加控制参数
+    paramTypes.push_back(Type::getInt1Ty(Context));
+    // 添加bunker函数参数
+    for (const auto& arg : bunkerFunc->args()) {
+        paramTypes.push_back(arg.getType());
+    }
+    // 添加target函数参数
+    for (const auto& arg : targetFunc->args()) {
+        paramTypes.push_back(arg.getType());
+    }
+    // 创建返回类型
+    Type* returnType;
+    if (bunkerFunc->getReturnType()->isVoidTy() && targetFunc->getReturnType()->isVoidTy()) {
+        LOG_DEBUG("createFusedFunctionType", "Both functions return void, creating void return type");
+        returnType = Type::getVoidTy(Context);
+    } else if (bunkerFunc->getReturnType()->isVoidTy()) {
+        LOG_DEBUG("createFusedFunctionType", 
+            "Bunker returns void, using target return type: {0}", 
+            getReadableTypeName(targetFunc->getReturnType()));
+        returnType = targetFunc->getReturnType();
+    } else if (targetFunc->getReturnType()->isVoidTy()) {
+        LOG_DEBUG("createFusedFunctionType", 
+            "Target returns void, using bunker return type: {0}", 
+            getReadableTypeName(bunkerFunc->getReturnType()));
+        returnType = bunkerFunc->getReturnType();
+    } else {
+        LOG_DEBUG("createFusedFunctionType", "Creating struct return type for non-void returns");
+        std::vector<Type*> structTypes;
+        structTypes.push_back(targetFunc->getReturnType());
+        structTypes.push_back(bunkerFunc->getReturnType());
+        returnType = StructType::create(Context, structTypes, 
+            "fused_return_" + bunkerFunc->getName().str() + "_" + targetFunc->getName().str());
+    }
+    LOG_DEBUG("createFusedFunctionType", 
+        "Created fused function type with return type: {0}", 
+        getReadableTypeName(returnType));
+    return FunctionType::get(returnType, paramTypes, false);
+}
+
+/**
+ * @brief 获取LLVM类型的可读字符串表示
+ * @param Ty LLVM类型指针
+ * @return 类型的可读字符串表示
+ * 
+ * 该函数将LLVM的Type对象转换为人类可读的字符串格式。
+ * 支持处理void、浮点数、整数、函数、指针、数组、结构体等类型。
+ * 如果输入类型为空指针,返回"null"。
+ */
+std::string Fusion::getReadableTypeName(Type* Ty) {
+    if (!Ty) {
+        return "null";
+    }
+
+    std::string TypeName;
+    raw_string_ostream OS(TypeName);
+
+    if (Ty->isVoidTy()) {
+        return "void";
+    } else if (Ty->isFloatingPointTy()) {
+        if (Ty->isHalfTy()) return "half";
+        if (Ty->isFloatTy()) return "float"; 
+        if (Ty->isDoubleTy()) return "double";
+        return "unknown_float";
+    } else if (Ty->isIntegerTy()) {
+        return "i" + std::to_string(cast<IntegerType>(Ty)->getBitWidth());
+    } else if (Ty->isFunctionTy()) {
+        FunctionType* FTy = cast<FunctionType>(Ty);
+        OS << "function(";
+        for (unsigned i = 0; i < FTy->getNumParams(); ++i) {
+            if (i > 0) OS << ", ";
+            OS << getReadableTypeName(FTy->getParamType(i));
+        }
+        if (FTy->isVarArg()) {
+            if (FTy->getNumParams() > 0) OS << ", ";
+            OS << "...";
+        }
+        OS << ") -> " << getReadableTypeName(FTy->getReturnType());
+    } else if (Ty->isPointerTy()) {
+        OS << getReadableTypeName(Ty->getPointerElementType()) << "*";
+    } else if (Ty->isArrayTy()) {
+        OS << "[" << Ty->getArrayNumElements() << " x " 
+           << getReadableTypeName(Ty->getArrayElementType()) << "]";
+    } else if (Ty->isStructTy()) {
+        StructType* STy = cast<StructType>(Ty);
+        if (STy->hasName()) {
+            OS << "struct." << STy->getName().str();
+        } else {
+            OS << "struct{";
+            for (unsigned i = 0; i < STy->getNumElements(); ++i) {
+                if (i > 0) OS << ", ";
+                OS << getReadableTypeName(STy->getElementType(i));
+            }
+            OS << "}";
+        }
+    } else if (Ty->isVectorTy()) {
+        OS << "<" << Ty->getVectorNumElements() << " x " 
+           << getReadableTypeName(Ty->getVectorElementType()) << ">";
+    } else if (Ty->isLabelTy()) {
+        return "label";
+    } else if (Ty->isMetadataTy()) {
+        return "metadata";
+    } else if (Ty->isTokenTy()) {
+        return "token";
+    } else {
+        return "unknown_type";
+    }
+    return OS.str();
+}
+
+/**
+ * @brief 更新函数调用点,将原始函数调用替换为融合后的函数调用
+ * 
+ * @param CI 原始的调用指令
+ * @param fusedFunc 融合后的新函数
+ * @param origFunc 原始被调用的函数
+ * @param otherFunc 另一个参与融合的函数
+ * @param isTarget 是否为目标函数的调用(true表示target调用,false表示bunker调用)
+ * 
+ * 该函数主要完成以下任务:
+ * 1. 构建新的函数调用,包括:
+ *    - 添加控制参数(布尔值,用于区分target/bunker调用)
+ *    - 添加原始函数的实际参数
+ *    - 添加另一个函数的默认参数
+ * 2. 处理返回值,包括:
+ *    - 从结构体返回值中提取正确的字段
+ *    - 进行必要的类型转换
+ * 3. 替换和清理原始调用
+ */
+void Fusion::updateCallSite(CallInst* CI, Function* fusedFunc, Function* origFunc, Function* otherFunc, bool isTarget) {
+    // 记录原始调用指令用于日志
+    std::string originalInstStr;
+    raw_string_ostream originalOS(originalInstStr);
+    CI->print(originalOS);
+    LOG_DEBUG("updateCallSite", "Original call instruction:\n  {0}", originalInstStr);
+    // 创建IR构建器,用于插入新指令
+    IRBuilder<> Builder(CI);
+    std::vector<Value*> Args;
+    // 添加控制参数(i1类型的布尔值)
+    // true表示这是target函数调用,false表示这是bunker函数调用
+    Args.push_back(ConstantInt::get(Type::getInt1Ty(CI->getContext()), isTarget));
+    LOG_DEBUG("updateCallSite", "Adding {0} control parameter", isTarget ? "target" : "bunker");
+    // 如果是target调用,需要先添加bunker函数的默认参数
+    // 因为融合函数的参数顺序是:控制参数 + bunker参数 + target参数
+    if (isTarget) {
+        LOG_DEBUG("updateCallSite", "Adding default bunker parameters:");
+        for (const auto& arg : otherFunc->args()) {
+            Type* ArgType = arg.getType();
+            LOG_DEBUG("updateCallSite", "  Parameter type: {0}", getReadableTypeName(ArgType));
+            if (ArgType->isPointerTy()) {
+                Args.push_back(ConstantPointerNull::get(cast<PointerType>(ArgType)));
+            } else if (ArgType->isIntegerTy()) {
+                Args.push_back(ConstantInt::get(ArgType, 0));
+            } else if (ArgType->isFloatingPointTy()) {
+                Args.push_back(ConstantFP::get(ArgType, 0.0));
+            } else {
+                Args.push_back(UndefValue::get(ArgType));
+            }
+        }
+    }
+    // 添加原始调用的实际参数
+    LOG_DEBUG("updateCallSite", "Adding original call parameters:");
+    for (unsigned i = 0; i < CI->getNumArgOperands(); ++i) {
+        Value* ArgVal = CI->getArgOperand(i);
+        LOG_DEBUG("updateCallSite", "  Argument {0}: type={1}", 
+            i, getReadableTypeName(ArgVal->getType()));
+        Args.push_back(ArgVal);
+    }
+    // 如果是bunker调用,需要在末尾添加target函数的默认参数
+    if (!isTarget) {
+        LOG_DEBUG("updateCallSite", "Adding default target parameters:");
+        for (const auto& arg : otherFunc->args()) {
+            Type* ArgType = arg.getType();
+            LOG_DEBUG("updateCallSite", "  Parameter type: {0}", getReadableTypeName(ArgType));
+            if (ArgType->isPointerTy()) {
+                Args.push_back(ConstantPointerNull::get(cast<PointerType>(ArgType)));
+            } else if (ArgType->isIntegerTy()) {
+                Args.push_back(ConstantInt::get(ArgType, 0));
+            } else if (ArgType->isFloatingPointTy()) {
+                Args.push_back(ConstantFP::get(ArgType, 0.0));
+            } else {
+                Args.push_back(UndefValue::get(ArgType));
+            }
+        }
+    }
+    // 创建对融合函数的新调用
+    CallInst* NewCI = Builder.CreateCall(fusedFunc, Args);
+    // 记录新调用指令用于日志
+    std::string newInstStr;
+    raw_string_ostream newOS(newInstStr);
+    NewCI->print(newOS);
+    LOG_DEBUG("updateCallSite", "New call instruction:\n  {0}", newInstStr);
+    // 处理非void返回值
+    if (!CI->getType()->isVoidTy()) {
+        LOG_DEBUG("updateCallSite", "Processing non-void return value of type: {0}",
+            getReadableTypeName(CI->getType()));
+        Value* ExtractedValue = nullptr;
+        // 如果融合函数返回结构体类型(包含两个字段:target返回值和bunker返回值)
+        if (StructType* STy = dyn_cast<StructType>(fusedFunc->getReturnType())) {
+            LOG_DEBUG("updateCallSite", "Extracting value from struct return type");
+            // 确保返回值是有效的结构体类型
+            if (STy->getNumElements() != 2) {
+                LOG_ERROR("updateCallSite", "Invalid fused function return type: expected 2 elements, got {0}",
+                    STy->getNumElements());
+                return;
+            }
+            // 获取正确的索引和对应的类型
+            unsigned idx = isTarget ? 0 : 1;
+            Type* expectedType = STy->getElementType(idx);
+            // 创建extractvalue指令
+            ExtractedValue = Builder.CreateExtractValue(NewCI, {idx}, 
+                "extracted_" + std::string(isTarget ? "target" : "bunker") + "_return");
+            LOG_DEBUG("updateCallSite", "Extracted value type: {0}",
+                getReadableTypeName(ExtractedValue->getType()));
+            // 验证提取的值类型
+            if (!ExtractedValue || ExtractedValue->getType() != expectedType) {
+                LOG_ERROR("updateCallSite", "Extracted value type mismatch: expected {0}, got {1}",
+                    getReadableTypeName(expectedType),
+                    ExtractedValue ? getReadableTypeName(ExtractedValue->getType()) : "null");
+                return;
+            }
+        } else {
+            ExtractedValue = NewCI;
+            LOG_DEBUG("updateCallSite", "Using direct return value");
+        }
+        // 如果需要,进行类型转换
+        // 支持的转换类型:指针、整数、浮点数
+        if (ExtractedValue && ExtractedValue->getType() != CI->getType()) {
+            LOG_DEBUG("updateCallSite", "Type conversion needed from {0} to {1}",
+                getReadableTypeName(ExtractedValue->getType()),
+                getReadableTypeName(CI->getType()));
+            // 确保源类型和目标类型都是有效的
+            if (!ExtractedValue->getType() || !CI->getType()) {
+                LOG_ERROR("updateCallSite", "Invalid type for conversion");
+                return;
+            }
+            if (CI->getType()->isPointerTy() && ExtractedValue->getType()->isPointerTy()) {
+                ExtractedValue = Builder.CreateBitCast(ExtractedValue, CI->getType(), 
+                    "conv_ptr_" + std::string(isTarget ? "target" : "bunker"));
+            } else if (CI->getType()->isIntegerTy() && ExtractedValue->getType()->isIntegerTy()) {
+                ExtractedValue = Builder.CreateIntCast(ExtractedValue, CI->getType(), true,
+                    "conv_int_" + std::string(isTarget ? "target" : "bunker"));
+            } else if (CI->getType()->isFloatingPointTy() && ExtractedValue->getType()->isFloatingPointTy()) {
+                if (CI->getType()->isDoubleTy()) {
+                    ExtractedValue = Builder.CreateFPExt(ExtractedValue, CI->getType(),
+                        "conv_fp_ext_" + std::string(isTarget ? "target" : "bunker"));
+                } else {
+                    ExtractedValue = Builder.CreateFPTrunc(ExtractedValue, CI->getType(),
+                        "conv_fp_trunc_" + std::string(isTarget ? "target" : "bunker"));
+                }
+            } else {
+                LOG_ERROR("updateCallSite", "Unsupported type conversion");
+                return;
+            }
+        }
+        // 验证最终返回值的类型是否正确
+        if (!ExtractedValue || ExtractedValue->getType() != CI->getType()) {
+            LOG_ERROR("updateCallSite", "Final value type mismatch: expected {0}, got {1}",
+                getReadableTypeName(CI->getType()),
+                ExtractedValue ? getReadableTypeName(ExtractedValue->getType()) : "null");
+            return;
+        }
+        // 用新的返回值替换原始调用的所有使用点
+        CI->replaceAllUsesWith(ExtractedValue);
+        LOG_DEBUG("updateCallSite", "Successfully replaced all uses of original call");
+    }
+    // 清理:删除原始调用指令
+    CI->eraseFromParent();
+    LOG_INFO("updateCallSite", "Successfully updated call site from {0} to {1}",
+        originalInstStr, newInstStr);
+}

+ 65 - 0
src/Fusion/Fusion.h

@@ -0,0 +1,65 @@
+#ifndef SLICE_FUSION_FUSION_H
+#define SLICE_FUSION_FUSION_H
+
+#include "llvm/IR/Function.h"
+#include "llvm/IR/Module.h"
+#include "llvm/IR/IRBuilder.h"
+#include "llvm/Transforms/Utils/Cloning.h"
+#include "../Util/CallGraphManager.h"
+#include <string>
+#include <set>
+#include <map>
+#include <vector>
+
+namespace slicefusion {
+
+struct SliceBlocks {
+    std::vector<llvm::BasicBlock*> blocks;
+    std::vector<llvm::BasicBlock*> backBlocks;
+};
+
+class Fusion {
+public:
+    Fusion(llvm::CallGraphManager& callGraph) : callGraph(callGraph) {}
+
+    bool matchFunctionsForFusion(
+        const std::set<std::string>& targetFunctions,
+        const std::set<std::string>& bunkerFunctions);
+
+    void performCodeFusion(llvm::Module &M);
+
+    const std::map<std::string, std::string>& getFusionPairs() const { 
+        return fusionPairs; 
+    }
+
+private:
+    llvm::CallGraphManager& callGraph;
+    std::map<std::string, std::string> fusionPairs;
+    
+    // 获取随机索引
+    size_t getRandomIndex(size_t max);
+
+    // 创建融合函数类型
+    llvm::FunctionType* createFusedFunctionType(
+        llvm::Function* bunkerFunc, 
+        llvm::Function* targetFunc, 
+        llvm::LLVMContext& Context);
+
+    // 更新调用点
+    void updateCallSite(
+        llvm::CallInst* CI, 
+        llvm::Function* fusedFunc, 
+        llvm::Function* origFunc, 
+        llvm::Function* otherFunc, 
+        bool isTarget);
+
+    // 获取可读的类型名称
+    std::string getReadableTypeName(llvm::Type* Ty);
+
+    // 判断是否需要条件包装
+    bool needsConditionalWrap(llvm::BasicBlock* BB);
+};
+
+} // namespace slicefusion
+
+#endif // SLICE_FUSION_FUSION_H

+ 430 - 0
src/Fusion/SliceAnalyzer.cpp

@@ -0,0 +1,430 @@
+#include "SliceAnalyzer.h"
+#include "../Util/LogSystem.h"
+#include "../Util/Utils.h"
+#include "llvm/Analysis/CFG.h"
+#include <functional>
+#include <queue>
+#include <algorithm>
+
+using namespace llvm;
+
+namespace slicefusion {
+
+/**
+ * @brief 检查基本块是否为关键点
+ * @param BB 待检查的基本块
+ * @return 如果是关键点返回true,否则返回false
+ * 
+ * 关键点定义:从入口块到出口块的所有路径必须经过该基本块。
+ * 也就是说,如果移除该基本块,将无法从入口到达出口。
+ */
+bool SliceAnalyzer::checkCriticalPoint(BasicBlock *BB) {
+    if (!BB) return false;
+    Function *F = BB->getParent();
+    if (!F) return false;
+    BasicBlock *Entry = &F->getEntryBlock();
+    BasicBlock *Exit = nullptr;
+    // 查找函数的退出块(包含return或unreachable指令的基本块)
+    for (BasicBlock &B : *F) {
+        if (isa<ReturnInst>(B.getTerminator()) || 
+            isa<UnreachableInst>(B.getTerminator())) {
+            Exit = &B;
+            break;
+        }
+    }
+    if (!Exit) return false;
+    // 定义用于检查路径可达性的递归lambda函数
+    std::set<BasicBlock*> visitedWithoutCurrent;
+    std::function<bool(BasicBlock*, BasicBlock*)> canReachExitWithout;
+    canReachExitWithout = [&canReachExitWithout, &visitedWithoutCurrent, BB]
+        (BasicBlock *Start, BasicBlock *Target) -> bool {
+            // 如果当前块是待检查块,返回false(模拟移除该块)
+            if (Start == BB) return false;
+            // 如果到达目标块,说明找到了一条路径
+            if (Start == Target) return true;
+            // 避免循环
+            if (visitedWithoutCurrent.count(Start)) return false;
+            visitedWithoutCurrent.insert(Start);
+            // 递归检查所有后继块
+            for (BasicBlock *Succ : successors(Start)) {
+                if (canReachExitWithout(Succ, Target)) {
+                    return true;
+                }
+            }
+            return false;
+        };
+    visitedWithoutCurrent.clear();
+    // 如果不能绕过当前块到达出口,则当前块是关键点
+    return !canReachExitWithout(Entry, Exit);
+}
+
+/**
+ * @brief 分析函数中的所有关键点
+ * @param F 待分析的函数
+ * @return 包含所有关键点的集合
+ * 
+ * 遍历函数中的所有基本块,检查每个块是否为关键点,
+ * 并记录日志显示找到的关键点数量。
+ */
+std::set<BasicBlock*> SliceAnalyzer::analyzeFunctionCriticalPoints(Function &F) {
+    std::set<BasicBlock*> criticalPoints;
+    std::string fname = F.getName().str();
+    // 检查每个基本块
+    for (BasicBlock &BB : F) {
+        if (checkCriticalPoint(&BB)) {
+            criticalPoints.insert(&BB);
+        }
+    }
+    // 记录分析结果
+    LOG_INFO("analyzeFunctionCriticalPoints", 
+        "Function {0} has {1} critical points", 
+        fname, 
+        criticalPoints.size());
+    return criticalPoints;
+}
+
+/**
+ * @brief 为函数创建代码分片
+ * @param F 待分片的函数
+ * @param callNode 包含函数调用信息的节点
+ * 
+ * 该函数根据关键点将函数分解成多个代码分片。
+ * 分片规则:
+ * 1. 每个分片至少包含一个关键点
+ * 2. 对于简单控制流的关键点,创建单块分片
+ * 3. 对于复杂控制流的关键点,尝试找到合适的终点创建多块分片
+ * 4. 每个分片与外部的连接必须满足:最多一个外部前驱和后继,且无条件跳转
+ */
+void SliceAnalyzer::createFunctionSlices(Function& F, CallNode& callNode) {
+    // 获取日志系统实例并启用当前函数的日志记录
+    auto& logger = logging::LogSystem::getInstance();
+    // logger.enableFunction("createFunctionSlices");
+    std::string fname = F.getName().str();
+    
+    // 如果不是目标函数或没有关键点,直接返回
+    if (!callNode.isTarget) {
+        return;
+    }
+    auto& criticalPoints = callNode.criticalPoints;
+    if (criticalPoints.empty()) {
+        return;
+    }
+    // 将入口块加入关键点集合
+    BasicBlock* entryBlock = &F.getEntryBlock();
+    criticalPoints.insert(entryBlock);
+    // 对关键点按名称排序
+    std::vector<BasicBlock*> orderedPoints(criticalPoints.begin(), criticalPoints.end());
+    std::sort(orderedPoints.begin(), orderedPoints.end(),
+        [](BasicBlock* a, BasicBlock* b) {
+            return a->getName() < b->getName();
+        });
+    std::set<BasicBlock*> processedBlocks;
+    std::vector<Slice>& slices = callNode.slices;
+    slices.clear();
+    // 定义一系列辅助函数
+    
+    // 检查基本块是否为入口块
+    auto isEntryBlock = [&F](BasicBlock* BB) {
+        return BB == &F.getEntryBlock();
+    };
+
+    // 检查基本块是否为出口块(没有后继节点的块)
+    auto isExitBlock = [](BasicBlock* BB) {
+        return BB->getTerminator()->getNumSuccessors() == 0;
+    };
+
+    // 检查基本块是否具有简单的控制流(最多一个前驱和一个后继)
+    auto hasSimpleFlow = [&](BasicBlock* BB) {
+        if (isEntryBlock(BB) || isExitBlock(BB)) {
+            return true;
+        }
+        size_t numSuccessors = std::distance(succ_begin(BB), succ_end(BB));
+        size_t numPredecessors = std::distance(pred_begin(BB), pred_end(BB));
+        LOG_DEBUG("createFunctionSlices", 
+            "Block {0} has {1} successors and {2} predecessors",
+            getNodeId(BB),
+            numSuccessors,
+            numPredecessors);
+        return numSuccessors <= 1 && numPredecessors <= 1;
+    };
+
+    // 使用BFS算法收集两个关键点之间的所有基本块
+    auto collectBlocksBetweenAndMark = [&processedBlocks](BasicBlock* start, BasicBlock* end) -> std::set<BasicBlock*> {
+        std::set<BasicBlock*> collectedBlocks;
+        std::queue<BasicBlock*> queue;
+        queue.push(start);
+        while (!queue.empty()) {
+            BasicBlock* current = queue.front();
+            queue.pop();
+            if (collectedBlocks.count(current)) {
+                continue;
+            }
+            collectedBlocks.insert(current);
+            if (current != end) {
+                for (BasicBlock* succ : successors(current)) {
+                    if (!collectedBlocks.count(succ)) {
+                        queue.push(succ);
+                    }
+                }
+            }
+        }
+        return collectedBlocks;
+    };
+
+    // 检查是否是条件分支指令(包括br和switch指令)
+    auto isConditionalBranch = [](BasicBlock* From, BasicBlock* To) {
+        if (BranchInst* BI = dyn_cast<BranchInst>(From->getTerminator())) {
+            return BI->isConditional();
+        }
+        if (SwitchInst* SI = dyn_cast<SwitchInst>(From->getTerminator())) {
+            return true;
+        }
+        return false;
+    };
+
+    // 检查基本块与分片外部的连接情况
+    // 返回true表示连接数量和类型都符合要求(最多一个外部前驱和后继,且没有条件跳转)
+    auto checkExternalConnections = [&](BasicBlock* BB, const std::set<BasicBlock*>& internalBlocks) {
+        size_t externalPredCount = 0;
+        size_t externalSuccCount = 0;
+        bool hasConditionalExternal = false;
+        // 检查外部前驱
+        for (BasicBlock* pred : predecessors(BB)) {
+            if (!internalBlocks.count(pred)) {
+                externalPredCount++;
+                // 检查前驱到当前块的跳转是否是条件跳转
+                if (isConditionalBranch(pred, BB)) {
+                    hasConditionalExternal = true;
+                    LOG_DEBUG("createFunctionSlices", 
+                        "Block {0} has conditional predecessor {1}",
+                        getNodeId(BB),
+                        getNodeId(pred));
+                }
+            }
+        }
+        // 检查外部后继
+        for (BasicBlock* succ : successors(BB)) {
+            if (!internalBlocks.count(succ)) {
+                externalSuccCount++;
+                // 检查当前块到后继的跳转是否是条件跳转
+                if (isConditionalBranch(BB, succ)) {
+                    hasConditionalExternal = true;
+                    LOG_DEBUG("createFunctionSlices", 
+                        "Block {0} has conditional successor {1}",
+                        getNodeId(BB),
+                        getNodeId(succ));
+                }
+            }
+        }
+        LOG_DEBUG("createFunctionSlices", 
+            "Block {0} has {1} external predecessors and {2} external successors, conditional: {3}",
+            getNodeId(BB),
+            externalPredCount,
+            externalSuccCount,
+            hasConditionalExternal ? "yes" : "no");
+        // 外部前驱和后继都必须小于等于1,且不能有条件跳转
+        return externalPredCount <= 1 && externalSuccCount <= 1 && !hasConditionalExternal;
+    };
+
+    // 在有序关键点列表中寻找下一个合适的分片终点
+    // 合适的终点需要满足外部连接的约束条件
+    auto findNextValidPoint = [&](size_t startIdx, BasicBlock* currentBlock) -> BasicBlock* {
+        for (size_t j = startIdx + 1; j < orderedPoints.size(); j++) {
+            BasicBlock* candidate = orderedPoints[j];
+            if (processedBlocks.count(candidate)) {
+                continue;
+            }
+            // 收集当前块到候选块之间的所有块
+            std::set<BasicBlock*> internalBlocks = collectBlocksBetweenAndMark(currentBlock, candidate);
+            // 检查候选块的外部连接数量是否符合要求
+            if (checkExternalConnections(candidate, internalBlocks)) {
+                LOG_DEBUG("createFunctionSlices", 
+                    "Found valid next point {0} for {1} with acceptable external connections",
+                    getNodeId(candidate),
+                    getNodeId(currentBlock));
+                return candidate;
+            }
+        }
+        return nullptr;
+    };
+
+    // 主循环:遍历所有关键点,创建分片
+    for (size_t i = 0; i < orderedPoints.size(); i++) {
+        BasicBlock* currentCritical = orderedPoints[i];
+        if (processedBlocks.count(currentCritical)) {
+            continue;  // 跳过已处理的基本块
+        }
+        
+        Slice newSlice;
+        if (hasSimpleFlow(currentCritical)) {
+            // 对于简单控制流的关键点,创建单块分片
+            LOG_DEBUG("createFunctionSlices", 
+                "Creating single-block slice for simple flow critical point: {0}",
+                getNodeId(currentCritical));
+            newSlice.blocks.push_back(currentCritical);
+            processedBlocks.insert(currentCritical);
+        } else {
+            // 对于复杂控制流的关键点,尝试找到合适的终点创建多块分片
+            // 如果找不到合适的终点,则创建单块分片
+            BasicBlock* nextPoint = findNextValidPoint(i, currentCritical);
+            if (!nextPoint) {
+                // 如果找不到下一个合适的关键点,只添加当前块
+                LOG_DEBUG("createFunctionSlices", 
+                    "No valid next point found, creating single-block slice for: {0}",
+                    getNodeId(currentCritical));
+                newSlice.blocks.push_back(currentCritical);
+                processedBlocks.insert(currentCritical);
+            } else {
+                // 使用BFS收集当前关键点到下一个关键点之间的所有块
+                LOG_DEBUG("createFunctionSlices", 
+                    "Creating multi-block slice from {0} to {1}",
+                    getNodeId(currentCritical),
+                    getNodeId(nextPoint));
+                // 收集并标记所有块
+                auto collectedBlocks = collectBlocksBetweenAndMark(currentCritical, nextPoint);
+                for (BasicBlock* block : collectedBlocks) {
+                    newSlice.blocks.push_back(block);
+                    processedBlocks.insert(block);
+                }
+            }
+        }
+        if (!newSlice.blocks.empty()) {
+            slices.push_back(newSlice);
+        }
+    }
+
+    // 记录分片创建的结果
+    callNode.slices_num = slices.size();
+    LOG_INFO("createFunctionSlices", 
+        "Created {0} slices for target function {1}",
+        slices.size(),
+        fname);
+
+    // 输出每个分片包含的基本块信息(调试用)
+    for (size_t i = 0; i < slices.size(); i++) {
+        std::string blockNames;
+        for (BasicBlock* block : slices[i].blocks) {
+            if (!blockNames.empty()) {
+                blockNames += ", ";
+            }
+            blockNames += getNodeId(block);
+        }
+        LOG_DEBUG("createFunctionSlices", 
+            "Slice {0} of function {1} contains blocks: {2}",
+            i,
+            fname,
+            blockNames);
+    }
+}
+
+/**
+ * @brief 统计函数中的融合点数量
+ * @param F 待分析的函数
+ * @param callNode 保存函数调用信息的节点
+ * 
+ * 遍历函数中的所有基本块,根据新的规则重新判定关键点:
+ * 1. 前驱节点数量 <= 1
+ * 2. 后继节点数量 <= 1
+ * 3. 与前驱和后继之间都不是条件跳转
+ */
+void SliceAnalyzer::countFusionPoints(Function& F, CallNode& callNode) {
+    auto& logger = logging::LogSystem::getInstance();
+    // logger.enableFunction("countFusionPoints");
+    std::string fname = F.getName().str();
+    LOG_INFO("countFusionPoints", "Counting fusion points for function: {0}", fname);
+    // 先获取原有的关键点
+    std::set<BasicBlock*> originalCriticalPoints = analyzeFunctionCriticalPoints(F);
+    // 清空可用性记录
+    callNode.isPredValid.clear();
+    callNode.isSuccValid.clear();
+    callNode.criticalPoints.clear();
+    // 只检查原有的关键点
+    for (BasicBlock* BB : originalCriticalPoints) {
+        // 获取前驱和后继数量
+        size_t numPred = std::distance(pred_begin(BB), pred_end(BB));
+        size_t numSucc = std::distance(succ_begin(BB), succ_end(BB));
+        LOG_DEBUG("countFusionPoints", 
+            "Checking critical point {0}: predecessors={1}, successors={2}",
+            getNodeId(BB),
+            numPred,
+            numSucc);
+        bool predValid = true;
+        bool succValid = true;
+        // 检查前驱
+        if (numPred <= 1) {
+            for (BasicBlock *Pred : predecessors(BB)) {
+                if (BranchInst *BI = dyn_cast<BranchInst>(Pred->getTerminator())) {
+                    if (BI->isConditional()) {
+                        LOG_DEBUG("countFusionPoints", 
+                            "Block {0} has conditional branch from predecessor {1}",
+                            getNodeId(BB),
+                            getNodeId(Pred));
+                        predValid = false;
+                    }
+                }
+                else if (isa<SwitchInst>(Pred->getTerminator())) {
+                    LOG_DEBUG("countFusionPoints", 
+                        "Block {0} has switch instruction from predecessor {1}",
+                        getNodeId(BB),
+                        getNodeId(Pred));
+                    predValid = false;
+                }
+            }
+        } else {
+            predValid = false;
+        }
+        // 检查后继
+        if (numSucc <= 1) {
+            for (BasicBlock *Succ : successors(BB)) {
+                if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
+                    if (BI->isConditional()) {
+                        LOG_DEBUG("countFusionPoints", 
+                            "Block {0} has conditional branch to successor {1}",
+                            getNodeId(BB),
+                            getNodeId(Succ));
+                        succValid = false;
+                    }
+                }
+                else if (isa<SwitchInst>(BB->getTerminator())) {
+                    LOG_DEBUG("countFusionPoints", 
+                        "Block {0} has switch instruction to successor {1}",
+                        getNodeId(BB),
+                        getNodeId(Succ));
+                    succValid = false;
+                }
+            }
+        } else {
+            succValid = false;
+        }
+        
+        // 修改:如果前驱有效,则后继必须无效
+        if (predValid) {
+            succValid = false;
+        }
+        
+        // 如果前驱或后继至少有一个有效,保留为关键点
+        if (predValid || succValid) {
+            LOG_INFO("countFusionPoints", 
+                "Critical point {0} is valid for fusion (pred_valid={1}, succ_valid={2})",
+                getNodeId(BB),
+                predValid ? "true" : "false",
+                succValid ? "true" : "false");
+            callNode.criticalPoints.insert(BB);
+            callNode.isPredValid[BB] = predValid;
+            callNode.isSuccValid[BB] = succValid;
+        } else {
+            LOG_DEBUG("countFusionPoints", 
+                "Critical point {0} is not valid for fusion (neither pred nor succ valid)",
+                getNodeId(BB));
+        }
+    }
+    // 更新关键点数量
+    callNode.points_num = callNode.criticalPoints.size();
+    LOG_INFO("countFusionPoints", 
+        "Found {0} valid fusion points out of {1} critical points in function {2}",
+        callNode.points_num,
+        originalCriticalPoints.size(),
+        fname);
+}
+
+} // namespace slicefusion

+ 32 - 0
src/Fusion/SliceAnalyzer.h

@@ -0,0 +1,32 @@
+#ifndef SLICE_FUSION_SLICE_H
+#define SLICE_FUSION_SLICE_H
+
+#include "llvm/IR/BasicBlock.h"
+#include "llvm/IR/Function.h"
+#include "llvm/IR/Module.h"
+#include "llvm/IR/Instructions.h"
+#include "../Util/CallGraphManager.h"
+#include <set>
+#include <vector>
+#include <queue>
+
+namespace slicefusion {
+
+class SliceAnalyzer {
+public:
+    // 检查给定的基本块是否是关键点
+    static bool checkCriticalPoint(llvm::BasicBlock *BB);
+    
+    // 分析函数中的关键点
+    static std::set<llvm::BasicBlock*> analyzeFunctionCriticalPoints(llvm::Function &F);
+    
+    // 创建函数分片
+    static void createFunctionSlices(llvm::Function& F, llvm::CallNode& callNode);
+    
+    // 统计函数中的融合点数量
+    static void countFusionPoints(llvm::Function& F, llvm::CallNode& callNode);
+};
+
+} // namespace slicefusion
+
+#endif // SLICE_FUSION_SLICE_H

+ 0 - 157
src/LogSystem.h

@@ -1,157 +0,0 @@
-// LogSystem.h
-#ifndef LOG_SYSTEM_H
-#define LOG_SYSTEM_H
-
-#include "llvm/Support/raw_ostream.h"
-#include <string>
-#include <map>
-#include <set>
-#include <sstream>
-
-namespace logging {
-
-enum class LogLevel {
-    TRACE,
-    DEBUG,
-    INFO,
-    WARNING,
-    ERROR,
-    NONE
-};
-
-class LogSystem {
-public:
-    static LogSystem& getInstance() {
-        static LogSystem instance;
-        return instance;
-    }
-
-    void setGlobalLevel(LogLevel level) {
-        globalLevel = level;
-    }
-
-    void setFunctionLevel(const std::string& funcName, LogLevel level) {
-        functionLevels[funcName] = level;
-    }
-
-    void enableFunction(const std::string& funcName) {
-        enabledFunctions.insert(funcName);
-    }
-
-    void disableFunction(const std::string& funcName) {
-        enabledFunctions.erase(funcName);
-    }
-
-    void setContextFunction(const std::string& funcName) {
-        currentFunctionName = funcName;
-    }
-
-    bool shouldLog(const std::string& funcName, LogLevel level) {
-        if (enabledFunctions.find(funcName) == enabledFunctions.end()) {
-            return false;
-        }
-
-        auto it = functionLevels.find(funcName);
-        if (it != functionLevels.end()) {
-            return level >= it->second;
-        }
-
-        return level >= globalLevel;
-    }
-
-    template<typename... Args>
-    void log(const std::string& funcName, LogLevel level, const char* format, Args... args) {
-        if (!shouldLog(funcName, level)) {
-            return;
-        }
-
-        std::string levelStr;
-        switch (level) {
-            case LogLevel::TRACE:   levelStr = "TRACE"; break;
-            case LogLevel::DEBUG:   levelStr = "DEBUG"; break;
-            case LogLevel::INFO:    levelStr = "INFO"; break;
-            case LogLevel::WARNING: levelStr = "WARNING"; break;
-            case LogLevel::ERROR:   levelStr = "ERROR"; break;
-            default: return;
-        }
-
-        std::string msg(format);
-        replaceAll(msg, args...);
-
-        llvm::errs() << "[" << levelStr << "]";
-        if (!currentFunctionName.empty()) {
-            llvm::errs() << "[" << currentFunctionName << "]";
-        }
-        llvm::errs() << "[" << funcName << "] " << msg << "\n";
-    }
-
-private:
-    LogSystem() : globalLevel(LogLevel::INFO) {}
-    LogLevel globalLevel;
-    std::map<std::string, LogLevel> functionLevels;
-    std::set<std::string> enabledFunctions;
-    std::string currentFunctionName;
-
-    // 递归终止条件
-    void replaceAll(std::string&) {}
-
-    // 递归替换函数
-    template<typename T, typename... Args>
-    void replaceAll(std::string& str, T&& value, Args&&... args) {
-        std::stringstream ss;
-        ss << std::forward<T>(value);
-        size_t pos = str.find("{0}");
-        if (pos != std::string::npos) {
-            str.replace(pos, 3, ss.str());
-        }
-        
-        // 移除已处理的参数,继续处理剩余参数
-        std::string rest = str;
-        size_t start = 0;
-        while ((pos = rest.find("{", start)) != std::string::npos) {
-            size_t end = rest.find("}", pos);
-            if (end != std::string::npos) {
-                std::string num = rest.substr(pos + 1, end - pos - 1);
-                
-                // 验证数字格式
-                bool isValidNumber = true;
-                for (char c : num) {
-                    if (!std::isdigit(c)) {
-                        isValidNumber = false;
-                        break;
-                    }
-                }
-                
-                if (isValidNumber) {
-                    // 手动将字符串转换为数字
-                    int n = 0;
-                    for (char c : num) {
-                        n = n * 10 + (c - '0');
-                    }
-                    
-                    if (n > 0) {  // 如果不是 {0}
-                        rest.replace(pos, end - pos + 1, "{" + std::to_string(n-1) + "}");
-                    }
-                }
-            }
-            start = pos + 1;
-        }
-        str = rest;
-        replaceAll(str, std::forward<Args>(args)...);
-    }
-};
-
-#define LOG_TRACE(func, ...) \
-    logging::LogSystem::getInstance().log(func, logging::LogLevel::TRACE, __VA_ARGS__)
-#define LOG_DEBUG(func, ...) \
-    logging::LogSystem::getInstance().log(func, logging::LogLevel::DEBUG, __VA_ARGS__)
-#define LOG_INFO(func, ...) \
-    logging::LogSystem::getInstance().log(func, logging::LogLevel::INFO, __VA_ARGS__)
-#define LOG_WARNING(func, ...) \
-    logging::LogSystem::getInstance().log(func, logging::LogLevel::WARNING, __VA_ARGS__)
-#define LOG_ERROR(func, ...) \
-    logging::LogSystem::getInstance().log(func, logging::LogLevel::ERROR, __VA_ARGS__)
-
-} // namespace logging
-
-#endif // LOG_SYSTEM_H

+ 43 - 2015
src/ModuleFusion.cpp

@@ -8,7 +8,17 @@
 #include "llvm/Support/raw_ostream.h"
 #include "llvm/Analysis/CFG.h"
 #include "llvm/Analysis/CallGraph.h"
-#include "LogSystem.h"
+#include "llvm/IR/IRBuilder.h"
+#include "llvm/Transforms/Utils/ValueMapper.h"
+#include "llvm/Transforms/Utils/Cloning.h"
+#include "llvm/Transforms/Utils/BasicBlockUtils.h"
+
+#include "Util/LogSystem.h"
+#include "Util/CallGraphManager.h"
+#include "Util/Utils.h"
+#include "Fusion/SliceAnalyzer.h"
+#include "Fusion/Fusion.h"
+
 #include <vector>
 #include <map>
 #include <set>
@@ -16,64 +26,27 @@
 #include <random>
 #include <algorithm>
 #include <string>
-#include "llvm/IR/IRBuilder.h"
-#include "llvm/Transforms/Utils/ValueMapper.h"
-#include "llvm/Transforms/Utils/Cloning.h"
-#include "llvm/Transforms/Utils/BasicBlockUtils.h"
 
 using namespace llvm;
 
-namespace {
-    struct Slice {
-        std::vector<BasicBlock*> blocks;
-    };
+extern logging::LogSystem logger;
 
+namespace {
     struct SliceBlocks {
         std::vector<BasicBlock*> blocks;
-        BasicBlock* phiBlock;
-    };
-
-    struct CallNode {
-        std::string name;
-        bool isTarget;
-        std::set<std::string> callers;
-        std::set<std::string> callees;
-        unsigned depth;
-        std::set<BasicBlock*> criticalPoints;
-        unsigned points_num; // 融合点个数
-        unsigned slices_num; //分片个数
-        std::vector<Slice> slices; // 存储函数分片
-        
-        CallNode() : name(""), isTarget(false), depth(0), points_num(0), slices_num(0) {}
-
-        CallNode(std::string n, bool target = false) 
-            : name(n), isTarget(target), depth(0), points_num(0), slices_num(0) {}
-    };
-
-    struct SliceTransition {
-        BasicBlock* bunkerLastBlock;    // bunker分片的最后一个基本块
-        BasicBlock* targetFirstBlock;   // target分片的第一个基本块
-        BasicBlock* targetLastBlock;    // target分片的最后一个基本块
-        BasicBlock* nextBunkerBlock;    // 下一个bunker分片的第一个基本块
+        std::vector<BasicBlock*> backBlocks;
     };
 
     struct CodeFusionPass : public ModulePass {
     public:
         static char ID;
-        CodeFusionPass() : ModulePass(ID) {}
+        CodeFusionPass() : ModulePass(ID), callGraph() {}
 
         bool runOnModule(Module &M) override {
             auto& logger = logging::LogSystem::getInstance();
-            logger.setGlobalLevel(logging::LogLevel::DEBUG);
+            logger.setGlobalLevel(logging::LogLevel::TRACE);
             // 配置Log输出权限
             logger.enableFunction("runOnModule");
-            // logger.enableFunction("dumpControlFlowGraph");
-            logger.enableFunction("buildCallGraph");
-            // logger.enableFunction("analyzeFunctionCriticalPoints");
-            // logger.enableFunction("calculateCallDepths");
-            logger.enableFunction("matchFunctionsForFusion");
-            logger.enableFunction("createFunctionSlices");
-            logger.enableFunction("countFusionPoints");
             logger.enableFunction("generateFusionMatchGraph");
             logger.enableFunction("performCodeFusion");
             logger.enableFunction("updateCallSite");
@@ -91,21 +64,33 @@ namespace {
                 }
             }
 
-            buildCallGraph(M);
-            analyzeFunctionCriticalPoints(M);
-            calculateCallDepths(M);
-            generateProjectCallGraph();
+            callGraph.buildCallGraph(M, targetFunctions);
+            callGraph.buildCallGraph(M, bunkerFunctions);
+
+            // 遍历模块中的所有函数,对每个函数调用SliceAnalyzer的分析函数
+            for (Function &F : M) {
+                if (!F.isDeclaration()) {
+                    std::string fname = F.getName().str();
+                    auto criticalPoints = slicefusion::SliceAnalyzer::analyzeFunctionCriticalPoints(F);
+                    // 将分析结果存储到callGraph中
+                    callGraph[fname].criticalPoints = criticalPoints;
+                }
+            }
+
+            // 生成项目调用图
+            callGraph.generateProjectCallGraph();
+            // 遍历模块中的所有函数,对每个函数调用SliceAnalyzer的分析函数
             for (Function &F : M) {
                 if(!F.isDeclaration()){
-                    dumpControlFlowGraph(F);
+                    callGraph.dumpControlFlowGraph(F);
                 }
             }
 
             LOG_INFO("runOnModule", "Creating slices for target functions");
             for (const auto& targetFuncName : targetFunctions) {
-                LOG_INFO("runOnModule", "targetFuncName: {0}",targetFuncName);
+                LOG_INFO("runOnModule", "targetFuncName: {0}", targetFuncName);
                 if (Function* F = M.getFunction(targetFuncName)) {
-                    createFunctionSlices(*F);
+                    slicefusion::SliceAnalyzer::createFunctionSlices(*F, callGraph[targetFuncName]);
                 } else {
                     LOG_ERROR("runOnModule", "Could not find function {0} in module", targetFuncName);
                 }
@@ -113,1985 +98,28 @@ namespace {
 
             LOG_INFO("runOnModule", "Creating fusion points for bunker functions");
             for (const auto& bunkerFuncName : bunkerFunctions) {
-                LOG_INFO("runOnModule", "bunkerFuncName: {0}",bunkerFuncName);
+                LOG_INFO("runOnModule", "bunkerFuncName: {0}", bunkerFuncName);
                 if (Function* F = M.getFunction(bunkerFuncName)) {
-                    countFusionPoints(*F);
-                    createFunctionSlices(*F);
+                    slicefusion::SliceAnalyzer::countFusionPoints(*F, callGraph[bunkerFuncName]);
                 } else {
                     LOG_ERROR("runOnModule", "Could not find function {0} in module", bunkerFuncName);
                 }
             }
 
-            if(matchFunctionsForFusion()){
-                generateFusionMatchGraph();
-                performCodeFusion(M);
+            // 创建一个Fusion对象并保持它的生命周期
+            slicefusion::Fusion fusion(callGraph);
+            if(fusion.matchFunctionsForFusion(targetFunctions, bunkerFunctions)) {
+                callGraph.generateFusionMatchGraph(targetFunctions, bunkerFunctions, fusion.getFusionPairs());
+                fusion.performCodeFusion(M);
             }
 
             return false;
         }
 
     private:
-        std::map<std::string, CallNode> callGraph;
-        std::map<std::string, unsigned> maxCallDepths;
+        CallGraphManager callGraph;
         std::set<std::string> targetFunctions;
         std::set<std::string> bunkerFunctions;
-        std::map<std::string, std::string> fusionPairs;
-
-        size_t getRandomIndex(size_t max) {
-            static unsigned seed = 0;
-            seed = (seed * 1103515245 + 12345) & 0x7fffffff;
-            return seed % max;
-        }
-
-        bool matchFunctionsForFusion() {
-            LOG_INFO("matchFunctionsForFusion", "Starting function matching process");
-            
-            if (bunkerFunctions.size() < targetFunctions.size()) {
-                LOG_WARNING("matchFunctionsForFusion", 
-                    "Insufficient bunker functions ({0}) for target functions ({1})", 
-                    bunkerFunctions.size(), 
-                    targetFunctions.size());
-                return false;
-            }
-
-            std::vector<std::string> sortedTargets(targetFunctions.begin(), targetFunctions.end());
-            std::sort(sortedTargets.begin(), sortedTargets.end(),
-                [this](const std::string& a, const std::string& b) {
-                    return callGraph[a].slices_num > callGraph[b].slices_num;  // 降序排列
-                });
-
-            std::vector<std::string> availableBunkers(bunkerFunctions.begin(), bunkerFunctions.end());
-
-            for (const auto& targetFunc : sortedTargets) {
-                const auto& targetNode = callGraph[targetFunc];
-                size_t requiredPoints = targetNode.slices_num;
-
-                bool matched = false;
-                while (!availableBunkers.empty() && !matched) {
-                    size_t idx = getRandomIndex(availableBunkers.size());
-                    const auto& bunkerFunc = availableBunkers[idx];
-                    const auto& bunkerNode = callGraph[bunkerFunc];
-
-                    if (bunkerNode.points_num >= requiredPoints) {
-                        fusionPairs[targetFunc] = bunkerFunc;
-                        availableBunkers.erase(availableBunkers.begin() + idx);
-                        matched = true;
-                        LOG_INFO("matchFunctionsForFusion", 
-                            "Matched target {0} ({1} slices) with bunker {2} ({3} fusion points)",
-                            targetFunc, 
-                            targetNode.slices_num,
-                            bunkerFunc,
-                            bunkerNode.points_num);
-                    } else {
-                        availableBunkers.erase(availableBunkers.begin() + idx);
-                    }
-                }
-
-                if (!matched) {
-                    LOG_ERROR("matchFunctionsForFusion", 
-                        "Could not find suitable bunker function for target {0}", 
-                        targetFunc);
-                    return false;
-                }
-                // LOG_INFO("matchFunctionsForFusion", "Remaining bunker functions after matching {0}:", targetFunc);
-                // for (const auto& remainingBunker : availableBunkers) {
-                //     const auto& bunkerNode = callGraph[remainingBunker];
-                //     LOG_INFO("matchFunctionsForFusion", 
-                //         "    {0} (Critical Points: {1})", 
-                //         remainingBunker, 
-                //         bunkerNode.criticalPoints.size());
-                // }
-            }
-            return true;
-        }
-
-        void generateFusionMatchGraph() {
-            LOG_INFO("generateFusionMatchGraph", "Generating fusion match visualization");
-            
-            errs() << "```mermaid\n";
-            errs() << "graph LR\n";
-            errs() << "    %% Fusion Match Graph\n";
-            errs() << "    %% Left side: Target Project, Right side: Bunker Project\n\n";
-            
-            errs() << "    subgraph Target[\"Target Project\"]\n";
-            errs() << "        direction TB\n";
-            for (const auto& targetFunc : targetFunctions) {
-                std::string nodeId = sanitizeNodeId(targetFunc);
-                std::string sliceNum = std::to_string(callGraph[targetFunc].slices_num);
-                errs() << "        " << nodeId << "[\"" << targetFunc 
-                    << "\\nSliceNum: " << sliceNum
-                    << "\"]:::target\n";
-            }
-            errs() << "    end\n\n";
-            
-            errs() << "    subgraph Bunker[\"Bunker Project\"]\n";
-            errs() << "        direction TB\n";
-            for (const auto& bunkerFunc : bunkerFunctions) {
-                std::string nodeId = sanitizeNodeId(bunkerFunc);
-                std::string criticalPoints = std::to_string(callGraph[bunkerFunc].criticalPoints.size());
-                errs() << "        " << nodeId << "[\"" << bunkerFunc 
-                    << "\\nCritical Points: " << criticalPoints
-                    << "\"]:::bunker\n";
-            }
-            errs() << "    end\n\n";
-            
-            errs() << "    %% Fusion Matches\n";
-            for (const auto& match : fusionPairs) {
-                std::string targetId = sanitizeNodeId(match.first);
-                std::string bunkerId = sanitizeNodeId(match.second);
-                errs() << "    " << targetId << " ==>|fusion| " << bunkerId << "\n";
-            }
-            
-            errs() << "    %% Styles\n";
-            errs() << "    classDef target fill:#f96,stroke:#333,stroke-width:2px\n";
-            errs() << "    classDef bunker fill:#9cf,stroke:#333,stroke-width:2px\n";
-            errs() << "    style Target fill:#fff,stroke:#f96,stroke-width:2px\n";
-            errs() << "    style Bunker fill:#fff,stroke:#9cf,stroke-width:2px\n";
-            
-            errs() << "```\n\n";
-            
-            LOG_INFO("generateFusionMatchGraph", 
-                "Generated visualization with {0} target functions and {1} bunker functions", 
-                targetFunctions.size(), 
-                bunkerFunctions.size());
-            LOG_INFO("generateFusionMatchGraph", 
-                "Total fusion matches: {0}", 
-                fusionPairs.size());
-        }
-
-        void countFusionPoints(Function& F) {
-            std::string fname = F.getName().str();
-            
-            if (targetFunctions.find(fname) != targetFunctions.end()) {
-                return;
-            }
-
-            auto& criticalPoints = callGraph[fname].criticalPoints;
-            if (criticalPoints.empty()) {
-                callGraph[fname].points_num = 0;
-                return;
-            }
-            callGraph[fname].points_num = criticalPoints.size();
-
-            LOG_INFO("countFusionPoints", 
-                "Counted {0} fusion points for bunker function {1}",
-                criticalPoints.size(),
-                fname);
-        }
-
-        void createFunctionSlices(Function& F) {
-            std::string fname = F.getName().str();
-            
-            if (!callGraph[fname].isTarget) {
-                return;
-            }
-
-            auto& criticalPoints = callGraph[fname].criticalPoints;
-            if (criticalPoints.empty()) {
-                return;
-            }
-
-            BasicBlock* entryBlock = &F.getEntryBlock();
-            criticalPoints.insert(entryBlock);
-
-            std::vector<BasicBlock*> orderedPoints(criticalPoints.begin(), criticalPoints.end());
-            std::sort(orderedPoints.begin(), orderedPoints.end(),
-                [](BasicBlock* a, BasicBlock* b) {
-                    return a->getName() < b->getName();
-                });
-
-            std::set<BasicBlock*> processedBlocks;
-            std::vector<Slice>& slices = callGraph[fname].slices;
-            slices.clear(); // 确保开始前清空
-
-            for (size_t i = 0; i < orderedPoints.size(); i++) {
-                BasicBlock* currentCritical = orderedPoints[i];
-                
-                if (processedBlocks.count(currentCritical)) {
-                    continue;
-                }
-
-                size_t numSuccessors = std::distance(succ_begin(currentCritical), succ_end(currentCritical));
-                size_t numPredecessors = std::distance(pred_begin(currentCritical), pred_end(currentCritical));
-
-                Slice newSlice;
-                if (numSuccessors <= 1 && numPredecessors <= 1) {
-                    newSlice.blocks.push_back(currentCritical);
-                    processedBlocks.insert(currentCritical);
-                } else {
-                    BasicBlock* nextCritical = nullptr;
-                    for (size_t j = i + 1; j < orderedPoints.size(); j++) {
-                        if (!processedBlocks.count(orderedPoints[j])) {
-                            nextCritical = orderedPoints[j];
-                            break;
-                        }
-                    }
-
-                    if (!nextCritical) {
-                        newSlice.blocks.push_back(currentCritical);
-                        processedBlocks.insert(currentCritical);
-                    } else {
-                        std::queue<BasicBlock*> queue;
-                        queue.push(currentCritical);
-                        while (!queue.empty()) {
-                            BasicBlock* current = queue.front();
-                            queue.pop();
-                            if (processedBlocks.count(current)) {
-                                continue;
-                            }
-                            processedBlocks.insert(current);
-                            newSlice.blocks.push_back(current);
-                            if (current != nextCritical) {
-                                for (BasicBlock* succ : successors(current)) {
-                                    if (!processedBlocks.count(succ) && 
-                                        (succ == nextCritical || !criticalPoints.count(succ))) {
-                                        queue.push(succ);
-                                    }
-                                }
-                            }
-                        }
-                    }
-                }
-                if (!newSlice.blocks.empty()) {
-                    slices.push_back(newSlice);
-                }
-            }
-
-            callGraph[fname].slices_num = slices.size();
-
-            LOG_INFO("createFunctionSlices", 
-                "Created {0} slices for target function {1}",
-                slices.size(),
-                fname);
-
-            for (size_t i = 0; i < slices.size(); i++) {
-                std::string blockNames;
-                for (BasicBlock* block : slices[i].blocks) {
-                    if (!blockNames.empty()) {
-                        blockNames += ", ";
-                    }
-                    blockNames += getNodeId(block);
-                }
-                LOG_DEBUG("createFunctionSlices", 
-                    "Slice {0} of function {1} contains blocks: {2}",
-                    i,
-                    fname,
-                    blockNames);
-            }
-        }
-
-        bool isTargetCode(Function &F) {
-            if (MDNode *MD = F.getMetadata("project_source")) {
-                if (MDString *ProjectStr = dyn_cast<MDString>(MD->getOperand(0))) {
-                    std::string projectName = ProjectStr->getString().str();
-                    return (projectName == "Target");
-                }
-            }
-            return false;
-        }
-
-        void dumpControlFlowGraph(Function &F) {
-            LOG_INFO("dumpControlFlowGraph", "Generating control flow graph for function: {0}", 
-                F.getName().str());
-            
-            if (F.empty()) {
-                LOG_WARNING("dumpControlFlowGraph", "Function is empty!");
-                return;
-            }
-
-            LOG_INFO("dumpControlFlowGraph", "Starting Mermaid graph generation");
-            errs() << "```mermaid: " << F.getName().str() << "\n";
-            errs() << "graph TD\n";
-            
-            for (BasicBlock &BB : F) {
-                std::string nodeId = getNodeId(&BB);
-                if (!nodeId.empty() && nodeId[0] == '%') {
-                    nodeId = nodeId.substr(1);
-                }
-                std::replace(nodeId.begin(), nodeId.end(), '.', '_');
-                std::replace(nodeId.begin(), nodeId.end(), ' ', '_');
-                std::replace(nodeId.begin(), nodeId.end(), '%', '_');
-                std::replace(nodeId.begin(), nodeId.end(), '-', '_');
-
-                LOG_TRACE("dumpControlFlowGraph", "Processing block with ID: {0}", nodeId);
-
-                std::string blockContent;
-                raw_string_ostream contentOS(blockContent);
-                
-                contentOS << "Block " << nodeId << ":\\n";
-                
-                for (Instruction &I : BB) {
-                    std::string instStr;
-                    raw_string_ostream instOS(instStr);
-                    I.print(instOS);
-                    instOS.flush();
-                    
-                    std::replace(instStr.begin(), instStr.end(), '"', '\'');
-                    std::replace(instStr.begin(), instStr.end(), '\n', ' ');
-                    
-                    if (instStr.length() > 50) {
-                        LOG_TRACE("dumpControlFlowGraph", "Truncating long instruction in block {0}", nodeId);
-                        instStr = instStr.substr(0, 47) + "...";
-                    }
-                    
-                    contentOS << instStr << "\\n";
-                }
-                contentOS.flush();
-
-                std::string fname = F.getName().str();
-
-                if (callGraph[fname].criticalPoints.count(&BB)) {
-                    LOG_TRACE("dumpControlFlowGraph", "Marking block {0} as critical", nodeId);
-                    errs() << "    " << nodeId << "[\"" << blockContent << "\"]:::critical\n";
-                } else {
-                    errs() << "    " << nodeId << "[\"" << blockContent << "\"]\n";
-                }
-
-                for (BasicBlock *Succ : successors(&BB)) {
-                    std::string succId;
-                    raw_string_ostream succOS(succId);
-                    Succ->printAsOperand(succOS, false);
-                    succOS.flush();
-                    
-                    if (!succId.empty() && succId[0] == '%') {
-                        succId = succId.substr(1);
-                    }
-                    
-                    std::replace(succId.begin(), succId.end(), '.', '_');
-                    std::replace(succId.begin(), succId.end(), ' ', '_');
-                    std::replace(succId.begin(), succId.end(), '%', '_');
-                    std::replace(succId.begin(), succId.end(), '-', '_');
-
-                    LOG_TRACE("dumpControlFlowGraph", "Processing edge from {0} to {1}", nodeId, succId);
-
-                    if (BranchInst *BI = dyn_cast<BranchInst>(BB.getTerminator())) {
-                        if (BI->isConditional()) {
-                            std::string condStr;
-                            raw_string_ostream condOS(condStr);
-                            BI->getCondition()->print(condOS);
-                            condOS.flush();
-                            
-                            bool isTrue = BI->getSuccessor(0) == Succ;
-                            LOG_TRACE("dumpControlFlowGraph", "Adding conditional branch edge: {0}", 
-                                isTrue ? "true" : "false");
-                            errs() << "    " << nodeId << " -->|" 
-                                << (isTrue ? "true" : "false") << "| " 
-                                << succId << "\n";
-                        } else {
-                            errs() << "    " << nodeId << " --> " << succId << "\n";
-                        }
-                    } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB.getTerminator())) {
-                        if (Succ == SI->getDefaultDest()) {
-                            LOG_TRACE("dumpControlFlowGraph", "Adding switch default edge");
-                            errs() << "    " << nodeId << " -->|default| " << succId << "\n";
-                        } else {
-                            for (auto Case : SI->cases()) {
-                                if (Case.getCaseSuccessor() == Succ) {
-                                    std::string caseStr;
-                                    raw_string_ostream caseOS(caseStr);
-                                    Case.getCaseValue()->print(caseOS);
-                                    LOG_TRACE("dumpControlFlowGraph", "Adding switch case edge: {0}", 
-                                        caseStr);
-                                    errs() << "    " << nodeId << " -->|case " 
-                                        << caseStr << "| " << succId << "\n";
-                                }
-                            }
-                        }
-                    } else {
-                        errs() << "    " << nodeId << " --> " << succId << "\n";
-                    }
-                }
-            }
-            errs() << "    classDef critical fill:#f96,stroke:#333,stroke-width:4px\n";
-            errs() << "```\n";
-            LOG_INFO("dumpControlFlowGraph", "Completed graph generation");
-        }
-
-        std::string getNodeId(BasicBlock *BB) {
-            std::string nodeId;
-            raw_string_ostream idOS(nodeId);
-            BB->printAsOperand(idOS, false);
-            idOS.flush();
-            return nodeId;
-        }
-
-        bool checkCriticalPoint(BasicBlock *BB) {
-            if (!BB) return false;
-            Function *F = BB->getParent();
-            if (!F) return false;
-            BasicBlock *Entry = &F->getEntryBlock();
-            BasicBlock *Exit = nullptr;
-            for (BasicBlock &B : *F) {
-                if (isa<ReturnInst>(B.getTerminator()) || 
-                    isa<UnreachableInst>(B.getTerminator())) {
-                    Exit = &B;
-                    break;
-                }
-            }
-            if (!Exit) return false;
-            std::set<BasicBlock*> visitedWithoutCurrent;
-            std::function<bool(BasicBlock*, BasicBlock*)> canReachExitWithout;
-            canReachExitWithout = [&canReachExitWithout, &visitedWithoutCurrent, BB]
-                (BasicBlock *Start, BasicBlock *Target) -> bool {
-                    if (Start == BB) return false;
-                    if (Start == Target) return true;
-                    
-                    if (visitedWithoutCurrent.count(Start)) return false;
-                    visitedWithoutCurrent.insert(Start);
-
-                    for (BasicBlock *Succ : successors(Start)) {
-                        if (canReachExitWithout(Succ, Target)) {
-                            return true;
-                        }
-                    }
-                    return false;
-                };
-            visitedWithoutCurrent.clear();
-            return !canReachExitWithout(Entry, Exit);
-        }
-
-        void analyzeFunctionCriticalPoints(Module &M) {
-            for (Function &F : M) {
-                if (!F.isDeclaration()) {
-                    std::string fname = F.getName().str();
-                    
-                    for (BasicBlock &BB : F) {
-                        if (checkCriticalPoint(&BB)) {
-                            callGraph[fname].criticalPoints.insert(&BB);
-                        }
-                    }
-                    LOG_INFO("analyzeFunctionCriticalPoints", 
-                        "Function {0} has {1} critical points", 
-                        fname, 
-                        callGraph[fname].criticalPoints.size());
-                }
-            }
-        }
-
-        void buildCallGraph(Module &M) {
-            LOG_INFO("buildCallGraph", "Building complete call graph");
-            for (Function &F : M) {
-                if (!F.isDeclaration()) {
-                    std::string fname = F.getName().str();
-                    bool isTarget = targetFunctions.find(fname) != targetFunctions.end();
-                    callGraph[fname] = CallNode(fname, isTarget);
-                }
-            }
-            for (Function &F : M) {
-                if (!F.isDeclaration()) {
-                    std::string callerName = F.getName().str();
-                    for (BasicBlock &BB : F) {
-                        for (Instruction &I : BB) {
-                            if (CallInst *CI = dyn_cast<CallInst>(&I)) {
-                                Function *CalledF = CI->getCalledFunction();
-                                if (CalledF && !CalledF->isDeclaration()) {
-                                    std::string calleeName = CalledF->getName().str();
-                                    callGraph[callerName].callees.insert(calleeName);
-                                    callGraph[calleeName].callers.insert(callerName);
-                                }
-                            }
-                        }
-                    }
-                }
-            }
-        }
-
-        void calculateCallDepths(Module &M) {
-            LOG_INFO("calculateCallDepths", "Calculating call depths for all functions in module");
-
-            maxCallDepths.clear();
-            
-            for (Function &F : M) {
-                if (F.isDeclaration()) {
-                    continue;
-                }
-                std::string startFunc = F.getName().str();
-                std::map<std::string, unsigned> depths;
-                std::queue<std::pair<std::string, unsigned>> queue;
-                std::set<std::string> visited;
-
-                queue.push(std::make_pair(startFunc, 0));
-                visited.insert(startFunc);
-
-                while (!queue.empty()) {
-                    std::string currentFunc = queue.front().first;
-                    unsigned depth = queue.front().second;
-                    queue.pop();
-                    depths[currentFunc] = depth;
-                    for (const std::string &caller : callGraph[currentFunc].callers) {
-                        if (visited.find(caller) == visited.end()) {
-                            queue.push(std::make_pair(caller, depth + 1));
-                            visited.insert(caller);
-                        }
-                    }
-                    for (const std::string &callee : callGraph[currentFunc].callees) {
-                        if (visited.find(callee) == visited.end()) {
-                            queue.push(std::make_pair(callee, depth + 1));
-                            visited.insert(callee);
-                        }
-                    }
-                }
-
-                for (const auto &pair : depths) {
-                    const std::string &func = pair.first;
-                    unsigned depth = pair.second;
-                    maxCallDepths[func] = std::max(maxCallDepths[func], depth);
-                }
-
-                LOG_DEBUG("calculateCallDepths", 
-                    "Function {0}: processed {1} related functions, max depth {2}", 
-                    startFunc, 
-                    depths.size(),
-                    maxCallDepths[startFunc]);
-            }
-
-            unsigned maxDepth = 0;
-            std::string deepestFunc;
-            for (const auto &pair : maxCallDepths) {
-                if (pair.second > maxDepth) {
-                    maxDepth = pair.second;
-                    deepestFunc = pair.first;
-                }
-            }
-            LOG_INFO("calculateCallDepths", 
-                "Analysis complete - Total functions: {0}, Maximum depth: {1} (in function: {2})", 
-                maxCallDepths.size(), 
-                maxDepth,
-                deepestFunc);
-        }
-
-        void generateProjectCallGraph() {
-            errs() << "```mermaid\n";
-            errs() << "graph TD\n";
-            errs() << "    %% Project Call Graph\n";
-            
-            for (const auto &pair : callGraph) {
-                const std::string &name = pair.first;
-                const CallNode &node = pair.second;
-                std::string nodeId = sanitizeNodeId(name);
-                std::string depth = std::to_string(maxCallDepths[name]);
-                std::string criticalPoints = std::to_string(node.criticalPoints.size());
-                std::string style = node.isTarget ? ":::target" : "";
-                errs() << "    " << nodeId << "[\"" << name 
-                    << "\\nDepth: " << depth 
-                    << "\\nCritical Points: " << criticalPoints
-                    << "\"]" << style << "\n";
-            }
-            
-            for (const auto &pair : callGraph) {
-                const std::string &name = pair.first;
-                const CallNode &node = pair.second;
-                std::string callerId = sanitizeNodeId(name);
-                for (const auto &callee : node.callees) {
-                    std::string calleeId = sanitizeNodeId(callee);
-                    errs() << "    " << callerId << " --> " << calleeId << "\n";
-                }
-            }
-            errs() << "    classDef target fill:#f96,stroke:#333,stroke-width:4px\n";
-            errs() << "```\n\n";
-        }
-
-        std::string sanitizeNodeId(const std::string &name) {
-            std::string id = name;
-            // 移除前导 %
-            if (!id.empty() && id[0] == '%') {
-                id = id.substr(1);
-            }
-            
-            // 替换非法字符
-            std::replace(id.begin(), id.end(), '.', '_');
-            std::replace(id.begin(), id.end(), ' ', '_');
-            std::replace(id.begin(), id.end(), '-', '_');
-            std::replace(id.begin(), id.end(), '%', '_');
-            
-            // 确保ID以字母开头
-            if (!id.empty() && std::isdigit(id[0])) {
-                id = "block_" + id;
-            }
-            
-            return id;
-        }
-
-        // 创建融合函数类型
-        FunctionType* createFusedFunctionType(Function* bunkerFunc, Function* targetFunc, LLVMContext& Context) {
-            LOG_DEBUG("createFusedFunctionType", 
-                "Creating fused type for bunker={0}({1}) and target={2}({3})", 
-                bunkerFunc->getName().str(),
-                getReadableTypeName(bunkerFunc->getReturnType()),
-                targetFunc->getName().str(),
-                getReadableTypeName(targetFunc->getReturnType()));
-
-            std::vector<Type*> paramTypes;
-            
-            // 添加控制参数
-            paramTypes.push_back(Type::getInt1Ty(Context));
-            
-            // 添加bunker函数参数
-            for (const auto& arg : bunkerFunc->args()) {
-                paramTypes.push_back(arg.getType());
-            }
-            
-            // 添加target函数参数
-            for (const auto& arg : targetFunc->args()) {
-                paramTypes.push_back(arg.getType());
-            }
-            
-            // 创建返回类型
-            Type* returnType;
-            if (bunkerFunc->getReturnType()->isVoidTy() && targetFunc->getReturnType()->isVoidTy()) {
-                LOG_DEBUG("createFusedFunctionType", "Both functions return void, creating void return type");
-                returnType = Type::getVoidTy(Context);
-            } else if (bunkerFunc->getReturnType()->isVoidTy()) {
-                LOG_DEBUG("createFusedFunctionType", 
-                    "Bunker returns void, using target return type: {0}", 
-                    getReadableTypeName(targetFunc->getReturnType()));
-                returnType = targetFunc->getReturnType();
-            } else if (targetFunc->getReturnType()->isVoidTy()) {
-                LOG_DEBUG("createFusedFunctionType", 
-                    "Target returns void, using bunker return type: {0}", 
-                    getReadableTypeName(bunkerFunc->getReturnType()));
-                returnType = bunkerFunc->getReturnType();
-            } else {
-                LOG_DEBUG("createFusedFunctionType", "Creating struct return type for non-void returns");
-                std::vector<Type*> structTypes;
-                structTypes.push_back(targetFunc->getReturnType());
-                structTypes.push_back(bunkerFunc->getReturnType());
-                returnType = StructType::create(Context, structTypes, 
-                    "fused_return_" + bunkerFunc->getName().str() + "_" + targetFunc->getName().str());
-            }
-
-            LOG_DEBUG("createFusedFunctionType", 
-                "Created fused function type with return type: {0}", 
-                getReadableTypeName(returnType));
-
-            return FunctionType::get(returnType, paramTypes, false);
-        }
-
-        // 更新调用点
-        void updateCallSite(CallInst* CI, Function* fusedFunc, Function* origFunc, Function* otherFunc, bool isTarget) {
-            // 记录原始调用指令
-            std::string originalInstStr;
-            raw_string_ostream originalOS(originalInstStr);
-            CI->print(originalOS);
-            LOG_DEBUG("updateCallSite", "Original call instruction:\n  {0}", originalInstStr);
-
-            IRBuilder<> Builder(CI);
-            std::vector<Value*> Args;
-            
-            // 添加控制参数
-            Args.push_back(ConstantInt::get(Type::getInt1Ty(CI->getContext()), isTarget));
-            
-            // 记录参数类型信息
-            LOG_DEBUG("updateCallSite", "Adding {0} control parameter", isTarget ? "target" : "bunker");
-            
-            // 如果是target调用,先添加bunker的默认参数
-            if (isTarget) {
-                LOG_DEBUG("updateCallSite", "Adding default bunker parameters:");
-                for (const auto& arg : otherFunc->args()) {
-                    Type* ArgType = arg.getType();
-                    LOG_DEBUG("updateCallSite", "  Parameter type: {0}", getReadableTypeName(ArgType));
-                    if (ArgType->isPointerTy()) {
-                        Args.push_back(ConstantPointerNull::get(cast<PointerType>(ArgType)));
-                    } else if (ArgType->isIntegerTy()) {
-                        Args.push_back(ConstantInt::get(ArgType, 0));
-                    } else if (ArgType->isFloatingPointTy()) {
-                        Args.push_back(ConstantFP::get(ArgType, 0.0));
-                    } else {
-                        Args.push_back(UndefValue::get(ArgType));
-                    }
-                }
-            }
-            
-            // 添加原始调用的参数
-            LOG_DEBUG("updateCallSite", "Adding original call parameters:");
-            for (unsigned i = 0; i < CI->getNumArgOperands(); ++i) {
-                Value* ArgVal = CI->getArgOperand(i);
-                LOG_DEBUG("updateCallSite", "  Argument {0}: type={1}", 
-                    i, getReadableTypeName(ArgVal->getType()));
-                Args.push_back(ArgVal);
-            }
-            
-            // 如果是bunker调用,后添加target的默认参数
-            if (!isTarget) {
-                LOG_DEBUG("updateCallSite", "Adding default target parameters:");
-                for (const auto& arg : otherFunc->args()) {
-                    Type* ArgType = arg.getType();
-                    LOG_DEBUG("updateCallSite", "  Parameter type: {0}", getReadableTypeName(ArgType));
-                    if (ArgType->isPointerTy()) {
-                        Args.push_back(ConstantPointerNull::get(cast<PointerType>(ArgType)));
-                    } else if (ArgType->isIntegerTy()) {
-                        Args.push_back(ConstantInt::get(ArgType, 0));
-                    } else if (ArgType->isFloatingPointTy()) {
-                        Args.push_back(ConstantFP::get(ArgType, 0.0));
-                    } else {
-                        Args.push_back(UndefValue::get(ArgType));
-                    }
-                }
-            }
-            
-            // 创建新的调用指令
-            CallInst* NewCI = Builder.CreateCall(fusedFunc, Args);
-            
-            // 记录新调用指令
-            std::string newInstStr;
-            raw_string_ostream newOS(newInstStr);
-            NewCI->print(newOS);
-            LOG_DEBUG("updateCallSite", "New call instruction:\n  {0}", newInstStr);
-            
-            // 处理返回值
-            if (!CI->getType()->isVoidTy()) {
-                LOG_DEBUG("updateCallSite", "Processing non-void return value of type: {0}",
-                    getReadableTypeName(CI->getType()));
-                    
-                Value* ExtractedValue = nullptr;
-                if (StructType* STy = dyn_cast<StructType>(fusedFunc->getReturnType())) {
-                    LOG_DEBUG("updateCallSite", "Extracting value from struct return type");
-                    
-                    // 确保返回值是有效的结构体类型
-                    if (STy->getNumElements() != 2) {
-                        LOG_ERROR("updateCallSite", "Invalid fused function return type: expected 2 elements, got {0}",
-                            STy->getNumElements());
-                        return;
-                    }
-                    
-                    // 获取正确的索引和对应的类型
-                    unsigned idx = isTarget ? 0 : 1;
-                    Type* expectedType = STy->getElementType(idx);
-                    
-                    // 创建extractvalue指令
-                    ExtractedValue = Builder.CreateExtractValue(NewCI, {idx}, 
-                        "extracted_" + std::string(isTarget ? "target" : "bunker") + "_return");
-                    
-                    LOG_DEBUG("updateCallSite", "Extracted value type: {0}",
-                        getReadableTypeName(ExtractedValue->getType()));
-                        
-                    // 验证提取的值类型
-                    if (!ExtractedValue || ExtractedValue->getType() != expectedType) {
-                        LOG_ERROR("updateCallSite", "Extracted value type mismatch: expected {0}, got {1}",
-                            getReadableTypeName(expectedType),
-                            ExtractedValue ? getReadableTypeName(ExtractedValue->getType()) : "null");
-                        return;
-                    }
-                } else {
-                    ExtractedValue = NewCI;
-                    LOG_DEBUG("updateCallSite", "Using direct return value");
-                }
-                
-                // 类型转换
-                if (ExtractedValue && ExtractedValue->getType() != CI->getType()) {
-                    LOG_DEBUG("updateCallSite", "Type conversion needed from {0} to {1}",
-                        getReadableTypeName(ExtractedValue->getType()),
-                        getReadableTypeName(CI->getType()));
-                    
-                    // 确保源类型和目标类型都是有效的
-                    if (!ExtractedValue->getType() || !CI->getType()) {
-                        LOG_ERROR("updateCallSite", "Invalid type for conversion");
-                        return;
-                    }
-                    
-                    if (CI->getType()->isPointerTy() && ExtractedValue->getType()->isPointerTy()) {
-                        ExtractedValue = Builder.CreateBitCast(ExtractedValue, CI->getType(), 
-                            "conv_ptr_" + std::string(isTarget ? "target" : "bunker"));
-                    } else if (CI->getType()->isIntegerTy() && ExtractedValue->getType()->isIntegerTy()) {
-                        ExtractedValue = Builder.CreateIntCast(ExtractedValue, CI->getType(), true,
-                            "conv_int_" + std::string(isTarget ? "target" : "bunker"));
-                    } else if (CI->getType()->isFloatingPointTy() && ExtractedValue->getType()->isFloatingPointTy()) {
-                        if (CI->getType()->isDoubleTy()) {
-                            ExtractedValue = Builder.CreateFPExt(ExtractedValue, CI->getType(),
-                                "conv_fp_ext_" + std::string(isTarget ? "target" : "bunker"));
-                        } else {
-                            ExtractedValue = Builder.CreateFPTrunc(ExtractedValue, CI->getType(),
-                                "conv_fp_trunc_" + std::string(isTarget ? "target" : "bunker"));
-                        }
-                    } else {
-                        LOG_ERROR("updateCallSite", "Unsupported type conversion");
-                        return;
-                    }
-                }
-                
-                // 验证最终的返回值
-                if (!ExtractedValue || ExtractedValue->getType() != CI->getType()) {
-                    LOG_ERROR("updateCallSite", "Final value type mismatch: expected {0}, got {1}",
-                        getReadableTypeName(CI->getType()),
-                        ExtractedValue ? getReadableTypeName(ExtractedValue->getType()) : "null");
-                    return;
-                }
-                
-                // 替换原始调用的所有使用
-                CI->replaceAllUsesWith(ExtractedValue);
-                LOG_DEBUG("updateCallSite", "Successfully replaced all uses of original call");
-            } else {
-                LOG_DEBUG("updateCallSite", "Void return type, no value processing needed");
-            }
-            
-            // 删除原始调用指令
-            CI->eraseFromParent();
-            LOG_INFO("updateCallSite", "Successfully updated call site from {0} to {1}",
-                originalInstStr, newInstStr);
-        }
-
-        // 添加一个辅助函数来获取可读的类型名称
-        std::string getReadableTypeName(Type* Ty) {
-            if (!Ty) return "null";
-            
-            if (Ty->isVoidTy()) return "void";
-            if (Ty->isIntegerTy()) return "i" + std::to_string(Ty->getIntegerBitWidth());
-            if (Ty->isFloatingPointTy()) return Ty->isDoubleTy() ? "double" : "float";
-            if (Ty->isPointerTy()) return getReadableTypeName(Ty->getPointerElementType()) + "*";
-            if (Ty->isArrayTy()) return "array of " + getReadableTypeName(Ty->getArrayElementType());
-            if (Ty->isStructTy()) {
-                if (StructType* STy = dyn_cast<StructType>(Ty)) {
-                    return STy->hasName() ? STy->getName().str() : "anonymous struct";
-                }
-                return "struct";
-            }
-            if (Ty->isFunctionTy()) return "function";
-            
-            return "unknown";
-        }
-
-        void performCodeFusion(Module &M) {
-            LOG_INFO("performCodeFusion", "Starting code fusion");
-            
-            for (const auto& fusion : fusionPairs) {
-                const std::string& targetName = fusion.first;
-                const std::string& bunkerName = fusion.second;
-                
-                Function* targetFunc = M.getFunction(targetName);
-                Function* bunkerFunc = M.getFunction(bunkerName);
-                
-                if (!targetFunc || !bunkerFunc) {
-                    LOG_ERROR("performCodeFusion", 
-                        "Cannot find functions: target={0}, bunker={1}", 
-                        targetName, bunkerName);
-                    continue;
-                }
-                
-                LOG_INFO("performCodeFusion", 
-                    "Processing function pair: target={0}, bunker={1}", 
-                    targetName, bunkerName);
-
-                // 创建融合函数类型
-                FunctionType* fusedType = createFusedFunctionType(bunkerFunc, targetFunc, M.getContext());
-                Function* fusedFunc = Function::Create(fusedType, bunkerFunc->getLinkage(),
-                    "fused_" + bunkerName, &M);
-            
-                // 创建入口基本块
-                BasicBlock* entryBlock = BasicBlock::Create(M.getContext(), "entry", fusedFunc);
-                if (!entryBlock) {
-                    LOG_ERROR("performCodeFusion", "Failed to create entry block");
-                    continue;
-                }
-                
-                IRBuilder<> Builder(entryBlock);
-            
-                // 获取控制参数(isTarget)
-                Value* isTarget = fusedFunc->arg_begin();
-            
-                // 创建参数映射
-                ValueToValueMapTy bunkerVMap, targetVMap;
-                unsigned argIdx = 1; // 跳过isTarget参数
-            
-                // 映射bunker函数参数
-                for (auto& arg : bunkerFunc->args()) {
-                    bunkerVMap[&arg] = fusedFunc->getArg(argIdx++);
-                }
-            
-                // 映射target函数参数
-                for (auto& arg : targetFunc->args()) {
-                    targetVMap[&arg] = fusedFunc->getArg(argIdx++);
-                }
-
-                // 获取target函数的分片
-                const auto& targetSlices = callGraph[targetName].slices;
-                size_t currentSliceIndex = 0;
-
-                // 获取bunker函数的关键点集合
-                const auto& criticalPoints = callGraph[bunkerName].criticalPoints;
-            
-                // 用于存储所有克隆的基本块
-                std::map<BasicBlock*, BasicBlock*> bunkerBlockMap;
-                std::map<BasicBlock*, BasicBlock*> targetBlockMap;
-                std::map<BasicBlock*, BasicBlock*> reverseTargetBlockMap;
-                std::map<BasicBlock*, BasicBlock*> reverseBunkerBlockMap;
-                std::vector<BasicBlock*> allFusedBlocks;
-
-                std::vector<SliceTransition> sliceTransitions;
-                std::vector<SliceBlocks> targetSliceBlocksList;
-                std::vector<SliceBlocks> bunkerSliceBlocksList;
-
-                // 存储条件块的映射
-                // std::map<BasicBlock*, BasicBlock*> condBlockMap;
-
-                // bool hasOpenBunkerSlice = false;
-
-                // // 遍历bunker函数的所有基本块
-                // for (BasicBlock& BB : *bunkerFunc) {
-                //     // 如果当前基本块是关键点且还有未插入的target分片
-                //     if (currentSliceIndex < targetSlices.size() && criticalPoints.count(&BB)) {
-                //         // 处理未闭合的bunker条件分片
-                //         if (hasOpenBunkerSlice) {
-                //             // 创建phi块作为bunker条件分片的结束
-                //             BasicBlock* bunkerPhiBlock = BasicBlock::Create(M.getContext(), 
-                //                 "bunker_phi_" + std::to_string(currentSliceIndex), fusedFunc);
-                            
-                //             // 将当前bunker条件分片的skip块指向phi块
-                //             IRBuilder<> Builder(currentBunkerSkipBlock);
-                //             Builder.CreateBr(bunkerPhiBlock);
-                            
-                //             // 创建target分片的条件块
-                //             BasicBlock* targetCondBlock = BasicBlock::Create(M.getContext(), 
-                //                 "target_slice_cond_" + std::to_string(currentSliceIndex), fusedFunc);
-                            
-                //             // 将bunker的phi块指向target的条件块
-                //             IRBuilder<> PhiBuilder(bunkerPhiBlock);
-                //             PhiBuilder.CreateBr(targetCondBlock);
-                            
-                //             hasOpenBunkerSlice = false;
-                //         }else {
-                //             // 直接创建target分片的条件块
-                //             BasicBlock* targetCondBlock = BasicBlock::Create(M.getContext(), 
-                //                 "target_slice_cond_" + std::to_string(currentSliceIndex), fusedFunc);
-                            
-                //             // 如果这是第一个块,从入口块跳转到这里
-                //             if (allFusedBlocks.empty()) {
-                //                 IRBuilder<> EntryBuilder(entryBlock);
-                //                 EntryBuilder.CreateBr(targetCondBlock);
-                //             }
-                //         }
-                //         BasicBlock* targetSkipBlock = BasicBlock::Create(M.getContext(), 
-                //             "target_slice_skip_" + std::to_string(currentSliceIndex), fusedFunc);
-
-                //         // 创建phi块用于合并控制流
-                //         BasicBlock* targetPhiBlock = BasicBlock::Create(M.getContext(),
-                //             "target_phi_" + std::to_string(currentSliceIndex), fusedFunc);
-
-                //         IRBuilder<> CondBuilder(targetCondBlock);
-                //         Value* shouldRunTarget = CondBuilder.CreateICmpEQ(isTarget, 
-                //             ConstantInt::getTrue(Type::getInt1Ty(M.getContext())));
-
-                //         // 克隆并插入target分片的基本块
-                //         for (BasicBlock* targetBB : currentSlice.blocks) {
-                //             BasicBlock* clonedTargetBB = CloneBasicBlock(targetBB, targetVMap, 
-                //                 "target_" + targetBB->getName(), fusedFunc);
-                //             targetBlockMap[targetBB] = clonedTargetBB;
-                //             allFusedBlocks.push_back(clonedTargetBB);
-                //         }
-
-                //         // 设置条件跳转
-                //         CondBuilder.CreateCondBr(shouldRunTarget, 
-                //             targetBlockMap[currentSlice.blocks.front()], 
-                //             targetSkipBlock);
-
-                //         // 修改target分片最后一个块的跳转到phi块
-                //         BasicBlock* lastTargetBB = targetBlockMap[currentSlice.blocks.back()];
-                //         if (BranchInst* BI = dyn_cast<BranchInst>(lastTargetBB->getTerminator())) {
-                //             IRBuilder<> Builder(lastTargetBB);
-                //             Builder.CreateBr(targetPhiBlock);
-                //             BI->eraseFromParent();
-                //         }
-
-                //         // 从skip块跳转到phi块
-                //         IRBuilder<> SkipBuilder(targetSkipBlock);
-                //         SkipBuilder.CreateBr(targetPhiBlock);
-                        
-                //         // 创建新的bunker条件分片
-                //         currentBunkerCondBlock = BasicBlock::Create(M.getContext(), 
-                //             "bunker_slice_cond_" + std::to_string(currentSliceIndex), fusedFunc);
-                //         currentBunkerSkipBlock = BasicBlock::Create(M.getContext(), 
-                //             "bunker_slice_skip_" + std::to_string(currentSliceIndex), fusedFunc);
-                            
-                //         // 从phi块跳转到下一个bunker条件块
-                //         IRBuilder<> PhiBuilder(targetPhiBlock);
-                //         PhiBuilder.CreateBr(currentBunkerCondBlock);
-                        
-                //         // 设置bunker条件块的分支
-                //         IRBuilder<> BunkerCondBuilder(currentBunkerCondBlock);
-                //         Value* shouldRunBunker = BunkerCondBuilder.CreateICmpEQ(isTarget, 
-                //             ConstantInt::getFalse(Type::getInt1Ty(M.getContext())));
-                //         BunkerCondBuilder.CreateCondBr(shouldRunBunker, 
-                //             clonedBunkerBB, 
-                //             currentBunkerSkipBlock);
-                            
-                //         hasOpenBunkerSlice = true;
-                //         currentSliceIndex++;
-                //     }
-                //     else{
-                //         // 克隆bunker基本块
-                //         BasicBlock* clonedBunkerBB = CloneBasicBlock(&BB, bunkerVMap, 
-                //             "bunker_" + BB.getName(), fusedFunc);
-                //         bunkerBlockMap[&BB] = clonedBunkerBB;
-                //         allFusedBlocks.push_back(clonedBunkerBB);
-                //     }
-                // }
-                // // 处理最后一个未闭合的bunker条件分片
-                // if (hasOpenBunkerSlice) {
-                //     BasicBlock* finalPhiBlock = BasicBlock::Create(M.getContext(), 
-                //         "bunker_final_phi", fusedFunc);
-                //     IRBuilder<> Builder(currentBunkerSkipBlock);
-                //     Builder.CreateBr(finalPhiBlock);
-                // }
-
-
-
-
-                // 遍历bunker函数的所有基本块
-                BasicBlock* currentBunkerSliceStart = nullptr;
-                std::vector<BasicBlock*> currentBunkerSlice;
-                sliceTransitions.clear();
-
-                // 在循环外声明phi块变量
-                BasicBlock* currentBunkerPhiBlock = nullptr;
-
-                for (BasicBlock& BB : *bunkerFunc) {
-                    // 如果当前基本块是关键点且还有未插入的target分片
-                    if (currentSliceIndex < targetSlices.size() && criticalPoints.count(&BB)) {
-                        // 记录分片转换信息
-                        SliceTransition transition;
-                        
-                        // 如果存在当前的bunker phi块,说明前一个bunker分片已完成
-                        if (currentBunkerPhiBlock) {
-                            transition.bunkerLastBlock = currentBunkerPhiBlock;
-                            // 为bunker分片的最后一个基本块添加到phi块的跳转
-                            if (!currentBunkerSlice.empty()) {
-                                BasicBlock* lastBunkerBlock = currentBunkerSlice.back();
-                                if (BranchInst* BI = dyn_cast<BranchInst>(lastBunkerBlock->getTerminator())) {
-                                    BI->eraseFromParent();
-                                }
-                                IRBuilder<> Builder(lastBunkerBlock);
-                                Builder.CreateBr(currentBunkerPhiBlock);
-                            }
-                            // 将phi块添加到分片和allFusedBlocks中
-                            allFusedBlocks.push_back(currentBunkerPhiBlock);
-                            SliceBlocks currentBunkerSliceBlocks;
-                            currentBunkerSliceBlocks.blocks = currentBunkerSlice;
-                            currentBunkerSliceBlocks.phiBlock = currentBunkerPhiBlock;
-                            bunkerSliceBlocksList.push_back(currentBunkerSliceBlocks);
-                        }
-                        
-                        // 为target分片创建条件块、跳过块和合并块
-                        BasicBlock* targetCondBlock = BasicBlock::Create(M.getContext(), 
-                            "target_cond_" + std::to_string(currentSliceIndex), fusedFunc);
-                        BasicBlock* targetSkipBlock = BasicBlock::Create(M.getContext(), 
-                            "target_skip_" + std::to_string(currentSliceIndex), fusedFunc);
-                        BasicBlock* targetPhiBlock = BasicBlock::Create(M.getContext(), 
-                            "target_phi_" + std::to_string(currentSliceIndex), fusedFunc);
-                        
-                        // bunker分片到target cond块的跳转
-                        if (currentBunkerPhiBlock) {
-                            IRBuilder<> bunkerPhiBuilder(currentBunkerPhiBlock);
-                            bunkerPhiBuilder.CreateBr(targetCondBlock);
-                        }
-
-                        // 将条件块加入到allFusedBlocks
-                        allFusedBlocks.push_back(targetCondBlock);
-                        allFusedBlocks.push_back(targetSkipBlock);
-                        
-                        // 在条件块中创建条件跳转
-                        IRBuilder<> targetCondBuilder(targetCondBlock);
-                        Value* shouldRunTarget = targetCondBuilder.CreateICmpEQ(isTarget, 
-                            ConstantInt::getTrue(Type::getInt1Ty(M.getContext())));
-                        
-                        // 克隆并插入target分片的基本块
-                        std::vector<BasicBlock*> targetSliceBlocks;
-                        for (BasicBlock* targetBB : targetSlices[currentSliceIndex].blocks) {
-                            BasicBlock* clonedTargetBB = CloneBasicBlock(targetBB, targetVMap, 
-                                "target_" + targetBB->getName(), fusedFunc);
-                            targetBlockMap[clonedTargetBB] = targetBB;
-                            reverseTargetBlockMap[targetBB] = clonedTargetBB;
-                            allFusedBlocks.push_back(clonedTargetBB);
-                            targetSliceBlocks.push_back(clonedTargetBB);
-                            LOG_INFO("performCodeFusion", 
-                                "adding: {0}",
-                                getNodeId(clonedTargetBB));
-                            }
-
-                        // 为最后一个实际基本块添加到phi块的跳转
-                        if (!targetSliceBlocks.empty()) {
-                            BasicBlock* lastActualBlock = targetSliceBlocks.back();
-                            if (BranchInst* BI = dyn_cast<BranchInst>(lastActualBlock->getTerminator())) {
-                                BI->eraseFromParent();
-                            }
-                            IRBuilder<> Builder(lastActualBlock);
-                            Builder.CreateBr(targetPhiBlock);
-                        }
-
-                        // 添加phi块到末尾
-                        allFusedBlocks.push_back(targetPhiBlock);
-
-                        SliceBlocks currentTargetSlice;
-                        for (BasicBlock* clonedBB : targetSliceBlocks) {
-                            LOG_INFO("performCodeFusion", 
-                                "before push Block ID: {0}",
-                                getNodeId(clonedBB));
-                        }
-                        currentTargetSlice.blocks = targetSliceBlocks;
-                        currentTargetSlice.phiBlock = targetPhiBlock;
-                        targetSliceBlocksList.push_back(currentTargetSlice);
-
-                        // 为bunker分片创建条件块、跳过块和合并块
-                        BasicBlock* bunkerCondBlock = BasicBlock::Create(M.getContext(), 
-                            "bunker_cond_" + std::to_string(currentSliceIndex), fusedFunc);
-                        BasicBlock* bunkerSkipBlock = BasicBlock::Create(M.getContext(), 
-                            "bunker_skip_" + std::to_string(currentSliceIndex), fusedFunc);
-                        BasicBlock* bunkerPhiBlock = BasicBlock::Create(M.getContext(), 
-                            "bunker_phi_" + std::to_string(currentSliceIndex), fusedFunc);
-                        currentBunkerPhiBlock = bunkerPhiBlock;
-
-                        // 将条件块加入到allFusedBlocks
-                        allFusedBlocks.push_back(bunkerCondBlock);
-                        allFusedBlocks.push_back(bunkerSkipBlock);
-                        
-                        // 在条件块中创建条件跳转
-                        IRBuilder<> bunkerCondBuilder(bunkerCondBlock);
-                        Value* shouldRunBunker = bunkerCondBuilder.CreateICmpEQ(isTarget, 
-                            ConstantInt::getFalse(Type::getInt1Ty(M.getContext())));
-                        
-                        // 克隆当前bunker基本块
-                        BasicBlock* clonedBunkerBB = CloneBasicBlock(&BB, bunkerVMap, 
-                            "bunker_" + BB.getName(), fusedFunc);
-                        bunkerBlockMap[clonedBunkerBB] = &BB;
-                        reverseBunkerBlockMap[&BB] = clonedBunkerBB;
-                        allFusedBlocks.push_back(clonedBunkerBB);
-                        
-                        // 设置初始条件跳转
-                        targetCondBuilder.CreateCondBr(shouldRunTarget, 
-                            targetSliceBlocks.front(), targetSkipBlock);  // 跳转到第一个实际target块
-
-                        // 设置skip块到phi块的跳转
-                        IRBuilder<> targetSkipBuilder(targetSkipBlock);
-                        targetSkipBuilder.CreateBr(targetPhiBlock);
-
-                        // target分片到bunker cond块的跳转
-                        IRBuilder<> targetPhiBuilder(targetPhiBlock);
-                        targetPhiBuilder.CreateBr(bunkerCondBlock);
-
-                        // 设置bunker条件跳转
-                        bunkerCondBuilder.CreateCondBr(shouldRunBunker, 
-                            clonedBunkerBB, bunkerSkipBlock);
-                            
-                        // 设置bunker skip块到phi块的跳转
-                        IRBuilder<> bunkerSkipBuilder(bunkerSkipBlock);
-                        bunkerSkipBuilder.CreateBr(bunkerPhiBlock);
-                        
-                        transition.targetFirstBlock = targetCondBlock;
-                        transition.targetLastBlock = targetPhiBlock;
-                        transition.nextBunkerBlock = bunkerCondBlock;
-                        sliceTransitions.push_back(transition);
-
-                        // 开始新的bunker分片
-                        currentBunkerSlice.clear();
-                        currentBunkerSlice.push_back(clonedBunkerBB);
-
-                        
-                        currentSliceIndex++;
-                    } else {
-                        // 克隆bunker基本块
-                        BasicBlock* clonedBunkerBB = CloneBasicBlock(&BB, bunkerVMap, 
-                            "bunker_" + BB.getName(), fusedFunc);
-                        bunkerBlockMap[clonedBunkerBB] = &BB;
-                        reverseBunkerBlockMap[&BB] = clonedBunkerBB;
-                        allFusedBlocks.push_back(clonedBunkerBB);
-                        currentBunkerSlice.push_back(clonedBunkerBB);
-                    }
-                }
-
-                // 处理最后一个bunker分片
-                if (currentBunkerPhiBlock) {
-                    sliceTransitions.back().bunkerLastBlock = currentBunkerPhiBlock;
-                    // 为最后一个bunker分片的最后一个基本块添加到phi块的跳转
-                    if (!currentBunkerSlice.empty()) {
-                        BasicBlock* lastBunkerBlock = currentBunkerSlice.back();
-                        if (BranchInst* BI = dyn_cast<BranchInst>(lastBunkerBlock->getTerminator())) {
-                            BI->eraseFromParent();
-                        }
-                        IRBuilder<> Builder(lastBunkerBlock);
-                        Builder.CreateBr(currentBunkerPhiBlock);
-                    }
-                    // 将最后的phi块添加到分片和allFusedBlocks中
-                    allFusedBlocks.push_back(currentBunkerPhiBlock);
-                    SliceBlocks currentBunkerSliceBlocks;
-                    currentBunkerSliceBlocks.blocks = currentBunkerSlice;
-                    currentBunkerSliceBlocks.phiBlock = currentBunkerPhiBlock;
-                    bunkerSliceBlocksList.push_back(currentBunkerSliceBlocks);
-                    // 为最后一个phi块添加返回指令
-                    IRBuilder<> PhiBuilder(currentBunkerPhiBlock);
-                    if (fusedFunc->getReturnType()->isVoidTy()) {
-                        PhiBuilder.CreateRetVoid();
-                    } else {
-                        // 创建默认返回值
-                        Value* defaultRetVal;
-                        Type* returnType = fusedFunc->getReturnType();
-                        
-                        if (StructType* STy = dyn_cast<StructType>(returnType)) {
-                            // 如果是结构体返回类型,创建一个零初始化的结构体
-                            defaultRetVal = ConstantAggregateZero::get(STy);
-                        } else if (returnType->isPointerTy()) {
-                            defaultRetVal = ConstantPointerNull::get(cast<PointerType>(returnType));
-                        } else if (returnType->isIntegerTy()) {
-                            defaultRetVal = ConstantInt::get(returnType, 0);
-                        } else if (returnType->isFloatingPointTy()) {
-                            defaultRetVal = ConstantFP::get(returnType, 0.0);
-                        } else {
-                            defaultRetVal = UndefValue::get(returnType);
-                        }
-                        
-                        PhiBuilder.CreateRet(defaultRetVal);
-                    }
-                }
-
-                // // 添加新的日志打印代码
-                // if (fusedFunc->getName() == "fused_createDynamicArray") {
-                //     LOG_INFO("performCodeFusion", "Listing all instructions after block cloning in function: {0}", 
-                //         fusedFunc->getName().str());
-                //     dumpControlFlowGraph(*fusedFunc);
-                // }
-
-                // // 在检查映射前添加调试信息
-                // LOG_INFO("performCodeFusion", "Dumping reverseBunkerBlockMap contents:");
-                // for (const auto& pair : reverseBunkerBlockMap) {
-                //     LOG_INFO("performCodeFusion", 
-                //         "Map entry: cloned={0} -> original={1}",
-                //         getNodeId(pair.first),
-                //         getNodeId(pair.second));
-                // }
-
-                // // 在检查映射前添加调试信息
-                // LOG_INFO("performCodeFusion", "Dumping BunkerBlockMap contents:");
-                // for (const auto& pair : bunkerBlockMap) {
-                //     LOG_INFO("performCodeFusion", 
-                //         "Map entry: original={0} -> cloned={1}",
-                //         getNodeId(pair.first),
-                //         getNodeId(pair.second));
-                // }
-
-                // // 输出所有bunkerSliceBlocksList中的块的id
-                // LOG_INFO("performCodeFusion", "bunkerSliceBlocksList size: {0}", bunkerSliceBlocksList.size());
-                // LOG_INFO("performCodeFusion", "Dumping bunkerSliceBlocksList contents:");
-                // for (const auto& sliceBlocks : bunkerSliceBlocksList) {
-                //     for (BasicBlock* clonedBB : sliceBlocks.blocks) {
-                //         LOG_INFO("performCodeFusion", 
-                //             "Block ID: {0}",
-                //             getNodeId(clonedBB));
-                //     }
-                // }
-
-                // // 在检查映射前添加调试信息
-                // LOG_INFO("performCodeFusion", "Dumping reverseTargetBlockMap contents:");
-                // for (const auto& pair : reverseTargetBlockMap) {
-                //     LOG_INFO("performCodeFusion", 
-                //         "Map entry: cloned={0} -> original={1}",
-                //         getNodeId(pair.first),
-                //         getNodeId(pair.second));
-                // }
-
-                // // 在检查映射前添加调试信息
-                // LOG_INFO("performCodeFusion", "Dumping TargetBlockMap contents:");
-                // for (const auto& pair : targetBlockMap) {
-                //     LOG_INFO("performCodeFusion", 
-                //         "Map entry: original={0} -> cloned={1}",
-                //         getNodeId(pair.first),
-                //         getNodeId(pair.second));
-                // }
-
-                // // 输出所有targetSliceBlocksList中的块的id
-                // LOG_INFO("performCodeFusion", "targetSliceBlocksList size: {0}", targetSliceBlocksList.size());
-                // LOG_INFO("performCodeFusion", "Dumping targetSliceBlocksList contents:");
-                // for (const auto& sliceBlocks : targetSliceBlocksList) {
-                //     for (BasicBlock* clonedBB : sliceBlocks.blocks) {
-                //         LOG_INFO("performCodeFusion", 
-                //             "Block ID: {0}",
-                //             getNodeId(clonedBB));
-                //     }
-                // }
-
-                // 修复target分片内的跳转
-                for (const auto& sliceBlocks : targetSliceBlocksList) {
-                    for (BasicBlock* clonedBB : sliceBlocks.blocks) {
-                        // 修复所有非终结指令
-                        for (Instruction &I : make_range(clonedBB->begin(), --clonedBB->end())) {
-                            RemapInstruction(&I, targetVMap, RF_NoModuleLevelChanges);
-                            
-                            if (PHINode* PHI = dyn_cast<PHINode>(&I)) {
-                                for (unsigned i = 0; i < PHI->getNumIncomingValues(); i++) {
-                                    BasicBlock* incomingBlock = PHI->getIncomingBlock(i);
-                                    LOG_DEBUG("performCodeFusion", 
-                                        "Processing PHI incoming block {0} in block {1}",
-                                        getNodeId(incomingBlock),
-                                        getNodeId(clonedBB));
-                                    if (reverseTargetBlockMap.count(incomingBlock)) {
-                                        BasicBlock* mappedBlock = reverseTargetBlockMap[incomingBlock];
-                                        PHI->setIncomingBlock(i, mappedBlock);
-                                    }
-                                    else{
-                                        LOG_WARNING("performCodeFusion",
-                                            "Incoming block {0} not found in reverseTargetBlockMap",
-                                            getNodeId(incomingBlock));
-                                    }
-                                }
-                            }
-                        }
-                        
-                        // 处理终结指令
-                        if (BranchInst* BI = dyn_cast<BranchInst>(clonedBB->getTerminator())) {
-                            // 检查是否是条件分支
-                            if (BI->isConditional()) {
-                                // 获取并映射条件值
-                                Value* originalCond = BI->getCondition();
-                                Value* mappedCond = MapValue(originalCond, targetVMap);
-                                
-                                if (mappedCond) {
-                                    if (mappedCond->getType()->isIntegerTy(1)) {
-                                        // 更新条件值
-                                        BI->setCondition(mappedCond);
-                                    } else {
-                                        LOG_ERROR("performCodeFusion", 
-                                            "Invalid condition type in block {0}: expected i1, got {1}",
-                                            getNodeId(clonedBB),
-                                            getReadableTypeName(mappedCond->getType()));
-                                    }
-                                }
-                            }
-                            
-                            // 检查是否是分片的最后一个基本块
-                            bool isLastInSlice = (clonedBB == sliceBlocks.blocks.back());
-                            
-                            if (!isLastInSlice) {
-                                // 获取当前克隆块对应的原始块
-                                BasicBlock* originalBB = targetBlockMap[clonedBB];
-                                if (!originalBB) {
-                                    LOG_ERROR("performCodeFusion", 
-                                        "Could not find original block for cloned block {0}",
-                                        getNodeId(clonedBB));
-                                    continue;
-                                }
-                                // 获取原始块的终结指令
-                                BranchInst* originalBI = dyn_cast<BranchInst>(originalBB->getTerminator());
-                                if (!originalBI) {
-                                    LOG_ERROR("performCodeFusion", 
-                                        "Could not find branch instruction in original block {0}",
-                                        getNodeId(originalBB));
-                                    continue;
-                                }
-
-                                // 修复克隆块的后继块
-                                for (unsigned i = 0; i < originalBI->getNumSuccessors(); i++) {
-                                    BasicBlock* originalSucc = originalBI->getSuccessor(i);
-                                    if (!originalSucc) {
-                                        LOG_WARNING("performCodeFusion", 
-                                            "Null successor found at index {0} in original block {1}",
-                                            i,
-                                            getNodeId(originalBB));
-                                        continue;
-                                    }
-
-                                    // 在reverseTargetBlockMap中查找对应的克隆后继块
-                                    if (reverseTargetBlockMap.count(originalSucc)) {
-                                        BasicBlock* mappedSucc = reverseTargetBlockMap[originalSucc];
-                                        if (mappedSucc) {
-                                            // LOG_DEBUG("performCodeFusion", 
-                                            //     "Remapping successor for block {0}: {1} -> {2}",
-                                            //     getNodeId(clonedBB),
-                                            //     getNodeId(originalSucc),
-                                            //     getNodeId(mappedSucc));
-                                            BI->setSuccessor(i, mappedSucc);
-                                        } else {
-                                            LOG_WARNING("performCodeFusion",
-                                                "Mapped successor is null for original block {0}",
-                                                getNodeId(originalSucc));
-                                        }
-                                    } else {
-                                        LOG_WARNING("performCodeFusion", 
-                                            "Could not find mapping for original successor block {0}",
-                                            getNodeId(originalSucc));
-                                    }
-                                }
-
-                                // // 正常修复跳转目标
-                                // for (unsigned i = 0; i < BI->getNumSuccessors(); i++) {
-                                //     BasicBlock* succ = BI->getSuccessor(i);
-                                //     if (reverseTargetBlockMap.count(succ)) {
-                                //         // 获取原始基本块
-                                //         BasicBlock* originalSucc = reverseTargetBlockMap[succ];
-                                //         if (targetBlockMap.count(originalSucc)) {
-                                //             errs() << "2331: \n";
-                                //             auto it = targetBlockMap.find(originalSucc);
-                                //             if (it != targetBlockMap.end()) {
-                                //                 errs() << "2332: \n";
-                                //                 BasicBlock* mappedSucc = it->second;
-                                //                 LOG_DEBUG("performCodeFusion", 
-                                //                     "Remapping successor {0} to {1}",
-                                //                     getNodeId(succ),
-                                //                     getNodeId(mappedSucc));
-                                //                 BI->setSuccessor(i, mappedSucc);
-                                //             }
-                                //         }
-                                //     } else {
-                                //         LOG_WARNING("performCodeFusion", 
-                                //             "Could not find mapping for successor block {0}",
-                                //             getNodeId(succ));
-                                //     }
-                                // }
-                            }
-                        }
-                    }
-                }
-
-                // 修复bunker块内的跳转
-                for (const auto& sliceBlocks : bunkerSliceBlocksList) {
-                    for (BasicBlock* clonedBB : sliceBlocks.blocks) {
-                        // 修复所有非终结指令
-                        for (Instruction &I : make_range(clonedBB->begin(), --clonedBB->end())) {
-                            RemapInstruction(&I, bunkerVMap, RF_NoModuleLevelChanges);
-                            
-                            if (PHINode* PHI = dyn_cast<PHINode>(&I)) {
-                                for (unsigned i = 0; i < PHI->getNumIncomingValues(); i++) {
-                                    BasicBlock* incomingBlock = PHI->getIncomingBlock(i);
-                                    LOG_DEBUG("performCodeFusion", 
-                                        "Processing PHI incoming block {0} in block {1}",
-                                        getNodeId(incomingBlock),
-                                        getNodeId(clonedBB));
-                                    if (reverseBunkerBlockMap.count(incomingBlock)) {
-                                        BasicBlock* mappedBlock = reverseBunkerBlockMap[incomingBlock];
-                                        PHI->setIncomingBlock(i, mappedBlock);
-                                    }
-                                    else{
-                                        LOG_WARNING("performCodeFusion",
-                                            "Incoming block {0} not found in reverseTargetBlockMap",
-                                            getNodeId(incomingBlock));
-                                    }
-                                }
-                            }
-                        }
-                    
-                        // 处理终结指令
-                        if (BranchInst* BI = dyn_cast<BranchInst>(clonedBB->getTerminator())) {
-                            // 检查是否是条件分支
-                            if (BI->isConditional()) {
-                                // 获取并映射条件值
-                                Value* originalCond = BI->getCondition();
-                                Value* mappedCond = MapValue(originalCond, bunkerVMap);
-                                
-                                if (mappedCond) {
-                                    if (mappedCond->getType()->isIntegerTy(1)) {
-                                        // 更新条件值
-                                        BI->setCondition(mappedCond);
-                                    } else {
-                                        LOG_ERROR("performCodeFusion", 
-                                            "Invalid condition type in block {0}: expected i1, got {1}",
-                                            getNodeId(clonedBB),
-                                            getReadableTypeName(mappedCond->getType()));
-                                    }
-                                }
-                            }
-                            
-                            // 检查是否是分片的最后一个基本块
-                            bool isLastInSlice = (clonedBB == sliceBlocks.blocks.back());
-                            
-                            if (!isLastInSlice) {
-                                // 获取当前克隆块对应的原始块
-                                BasicBlock* originalBB = bunkerBlockMap[clonedBB];
-                                if (!originalBB) {
-                                    LOG_ERROR("performCodeFusion", 
-                                        "Could not find original block for cloned block {0}",
-                                        getNodeId(clonedBB));
-                                    continue;
-                                }
-                                // 获取原始块的终结指令
-                                BranchInst* originalBI = dyn_cast<BranchInst>(originalBB->getTerminator());
-                                if (!originalBI) {
-                                    LOG_ERROR("performCodeFusion", 
-                                        "Could not find branch instruction in original block {0}",
-                                        getNodeId(originalBB));
-                                    continue;
-                                }
-
-                                // 修复克隆块的后继块
-                                for (unsigned i = 0; i < originalBI->getNumSuccessors(); i++) {
-                                    BasicBlock* originalSucc = originalBI->getSuccessor(i);
-                                    if (!originalSucc) {
-                                        LOG_WARNING("performCodeFusion", 
-                                            "Null successor found at index {0} in original block {1}",
-                                            i,
-                                            getNodeId(originalBB));
-                                        continue;
-                                    }
-
-                                    // 在reverseBunkerBlockMap中查找对应的克隆后继块
-                                    if (reverseBunkerBlockMap.count(originalSucc)) {
-                                        BasicBlock* mappedSucc = reverseBunkerBlockMap[originalSucc];
-                                        if (mappedSucc) {
-                                            // LOG_DEBUG("performCodeFusion", 
-                                            //     "Remapping successor for block {0}: {1} -> {2}",
-                                            //     getNodeId(clonedBB),
-                                            //     getNodeId(originalSucc),
-                                            //     getNodeId(mappedSucc));
-                                            BI->setSuccessor(i, mappedSucc);
-                                        } else {
-                                            LOG_WARNING("performCodeFusion",
-                                                "Mapped successor is null for original block {0}",
-                                                getNodeId(originalSucc));
-                                        }
-                                    } else {
-                                        LOG_WARNING("performCodeFusion", 
-                                            "Could not find mapping for original successor block {0}",
-                                            getNodeId(originalSucc));
-                                    }
-                                }
-                                // // 正常修复跳转目标
-                                // for (unsigned i = 0; i < BI->getNumSuccessors(); i++) {
-                                //     BasicBlock* succ = BI->getSuccessor(i);
-                                //     if (reverseBunkerBlockMap.count(succ)) {
-                                //         // 获取原始基本块
-                                //         BasicBlock* originalSucc = reverseBunkerBlockMap[succ];
-                                //         errs() << "2331: \n";
-                                //         if (bunkerBlockMap.count(originalSucc)) {
-                                //             errs() << "2332: \n";
-                                //             auto it = bunkerBlockMap.find(originalSucc);
-                                //             if (it != bunkerBlockMap.end()) {
-                                //                 BasicBlock* mappedSucc = it->second;
-                                //                 LOG_DEBUG("performCodeFusion", 
-                                //                     "Remapping successor {0} to {1}",
-                                //                     getNodeId(succ),
-                                //                     getNodeId(mappedSucc));
-                                //                 BI->setSuccessor(i, mappedSucc);
-                                //             }
-                                //         }
-                                //     } else {
-                                //         LOG_WARNING("performCodeFusion", 
-                                //             "Could not find mapping for bunker successor block {0}",
-                                //             getNodeId(succ));
-                                //     }
-                                // }
-                            }
-                        }
-                    }
-                }
-
-                // 从入口块创建跳转到第一个块
-                Builder.CreateBr(allFusedBlocks.front());
-
-                // 添加新的日志打印代码
-                LOG_INFO("performCodeFusion", "Listing all instructions after block cloning in function: {0}", 
-                    fusedFunc->getName().str());
-                dumpControlFlowGraph(*fusedFunc);
-
-                // 在处理返回值之前添加日志
-                LOG_DEBUG("performCodeFusion", 
-                    "Processing return values for fused function: {0}", 
-                    fusedFunc->getName().str());
-
-                LOG_DEBUG("performCodeFusion", 
-                    "Fused function return type: {0}", 
-                    getReadableTypeName(fusedFunc->getReturnType()));
-
-                // 处理返回值
-                if (!fusedFunc->getReturnType()->isVoidTy()) {
-                    Type* returnType = fusedFunc->getReturnType();
-
-                    if (StructType* STy = dyn_cast<StructType>(returnType)) {
-                        LOG_DEBUG("performCodeFusion", 
-                            "Processing struct return type with {0} elements",
-                            STy->getNumElements());
-
-                        // 处理 bunker 函数的返回指令
-                        for (auto& pair : bunkerBlockMap) {
-                            BasicBlock* BB = pair.first;
-                            if (!BB || BB->empty()) continue;
-
-                            std::vector<Instruction*> toDelete;  // 存储需要删除的指令
-                            bool foundReturn = false;
-                            
-                            for (BasicBlock::iterator I = BB->begin(); I != BB->end();) {
-                                Instruction* Inst = &*I;
-                                ++I;
-                                if (ReturnInst* RI = dyn_cast<ReturnInst>(Inst)){
-                                    // 添加额外的安全检查
-                                    if (!RI->getParent()) continue;
-                                    foundReturn = true;
-                                    IRBuilder<> Builder(RI);
-                                    Value* bunkerRetVal = RI->getReturnValue();
-                                    
-                                    // 创建结构体实例并正确初始化
-                                    Value* structVal = UndefValue::get(STy);
-                                    Type* targetType = STy->getElementType(0);
-                                    Type* bunkerType = STy->getElementType(1);
-
-                                    // 设置target返回值位置为默认值
-                                    LOG_DEBUG("performCodeFusion", "Setting default target return value");
-                                    Value* defaultTargetVal;
-                                    if (targetType->isPointerTy()) {
-                                        defaultTargetVal = ConstantPointerNull::get(cast<PointerType>(targetType));
-                                    } else if (targetType->isIntegerTy()) {
-                                        defaultTargetVal = ConstantInt::get(targetType, 0);
-                                    } else if (targetType->isFloatingPointTy()) {
-                                        defaultTargetVal = ConstantFP::get(targetType, 0.0);
-                                    } else {
-                                        defaultTargetVal = Constant::getNullValue(targetType);
-                                    }
-
-                                    // Value* mappedBunkerRetVal = MapValue(bunkerRetVal, bunkerVMap);
-                                    structVal = Builder.CreateInsertValue(structVal, defaultTargetVal, 0, "struct.target");
-                                    structVal = Builder.CreateInsertValue(structVal, bunkerRetVal, 1, "struct.bunker");
-                                    ReturnInst* NewRI = ReturnInst::Create(M.getContext(), structVal, RI);
-                                    ReplaceInstWithInst(RI, NewRI);
-                                    
-                                    LOG_DEBUG("performCodeFusion", 
-                                        "Created struct return for bunker block: {0} with types: target={1}, bunker={2}", 
-                                        getNodeId(BB),
-                                        getReadableTypeName(targetType),
-                                        getReadableTypeName(bunkerType));
-                                }else if (foundReturn) {
-                                    // 将返回指令之后的所有指令标记为待删除
-                                    toDelete.push_back(Inst);
-                                }
-                            }
-                            for (Instruction* I : toDelete) {
-                                LOG_DEBUG("performCodeFusion", 
-                                    "Removing extra instruction after return in block {0}: {1}",
-                                    getNodeId(BB),
-                                    I->getOpcodeName());
-                                I->eraseFromParent();
-                            }
-                        }
-
-                        // 处理 target 函数的返回指令
-                        for (auto& pair : targetBlockMap) {
-                            BasicBlock* BB = pair.first;
-                            if (!BB || BB->empty()) continue;
-
-                            std::vector<Instruction*> toDelete;  // 存储需要删除的指令
-                            bool foundReturn = false;
-                            
-                            for (BasicBlock::iterator I = BB->begin(); I != BB->end();) {
-                                Instruction* Inst = &*I;
-                                ++I;
-                                if (ReturnInst* RI = dyn_cast<ReturnInst>(Inst)){
-                                    // 添加额外的安全检查
-                                    if (!RI->getParent()) continue;
-                                    foundReturn = true;
-                                    IRBuilder<> Builder(RI);
-                                    Value* targetRetVal = RI->getReturnValue();
-                                    
-                                    // 创建结构体实例并正确初始化
-                                    Value* structVal = ConstantAggregateZero::get(STy);
-                                    Type* targetType = STy->getElementType(0);
-                                    Type* bunkerType = STy->getElementType(1);
-                                    
-                                    // 设置bunker返回值位置为默认值
-                                    Value* defaultBunkerVal;
-                                    if (bunkerType->isPointerTy()) {
-                                        defaultBunkerVal = ConstantPointerNull::get(cast<PointerType>(bunkerType));
-                                    } else if (bunkerType->isIntegerTy()) {
-                                        defaultBunkerVal = ConstantInt::get(bunkerType, 0);
-                                    } else if (bunkerType->isFloatingPointTy()) {
-                                        defaultBunkerVal = ConstantFP::get(bunkerType, 0.0);
-                                    } else {
-                                        defaultBunkerVal = Constant::getNullValue(bunkerType);
-                                    }
-
-                                    // Value* mappedTargetRetVal = MapValue(targetRetVal, targetVMap);
-
-                                    structVal = Builder.CreateInsertValue(structVal, targetRetVal, 0, "struct.target");
-                                    structVal = Builder.CreateInsertValue(structVal, defaultBunkerVal, 1, "struct.bunker");
-                                    ReturnInst* NewRI = ReturnInst::Create(M.getContext(), structVal, RI);
-                                    ReplaceInstWithInst(RI, NewRI);
-                                    
-                                    LOG_DEBUG("performCodeFusion", 
-                                        "Created struct return for target block: {0} with types: target={1}, bunker={2}", 
-                                        getNodeId(BB),
-                                        getReadableTypeName(targetType),
-                                        getReadableTypeName(bunkerType));
-                                }else if (foundReturn) {
-                                    // 将返回指令之后的所有指令标记为待删除
-                                    toDelete.push_back(Inst);
-                                }
-                            }
-                            for (Instruction* I : toDelete) {
-                                LOG_DEBUG("performCodeFusion", 
-                                    "Removing extra instruction after return in block {0}: {1}",
-                                    getNodeId(BB),
-                                    I->getOpcodeName());
-                                I->eraseFromParent();
-                            }
-                        }
-                    } else {
-                        // 处理非结构体返回值的情况
-                        LOG_DEBUG("performCodeFusion", 
-                            "Non-struct return type detected: {0}", 
-                            getReadableTypeName(returnType));
-
-                        // 处理 bunker 函数的返回指令
-                        for (auto& pair : bunkerBlockMap) {
-                            BasicBlock* BB = pair.first;
-
-                            LOG_DEBUG("performCodeFusion", "Processing bunker block: {0}", getNodeId(BB));
-                            
-                            if (!BB || BB->empty()) continue;
-
-                            std::vector<Instruction*> toDelete;  // 存储需要删除的指令
-                            bool foundReturn = false;
-
-                            for (BasicBlock::iterator I = BB->begin(); I != BB->end();) {
-                                Instruction* Inst = &*I;
-                                ++I;
-
-                                // 打印每条指令的信息
-                                std::string instStr;
-                                raw_string_ostream rso(instStr);
-                                Inst->print(rso);
-                                LOG_DEBUG("performCodeFusion", 
-                                    "Block {0} - Processing instruction: {1} (opcode: {2})", 
-                                    getNodeId(BB),
-                                    instStr,
-                                    Inst->getOpcodeName());
-
-                                if (ReturnInst* RI = dyn_cast<ReturnInst>(Inst)){
-                                    // 添加额外的安全检查
-                                    if (!RI->getParent()) continue;
-                                    foundReturn = true;
-                                    IRBuilder<> Builder(RI);
-                                    Value* bunkerRetVal = RI->getReturnValue();
-                                    // 先重映射返回值
-                                    // if (bunkerRetVal) {
-                                    //     LOG_DEBUG("performCodeFusion", "Mapping bunker return value");
-                                    //     bunkerRetVal = MapValue(bunkerRetVal, bunkerVMap);
-                                    // }
-                                    
-                                    if (!bunkerRetVal) {
-                                        LOG_DEBUG("performCodeFusion", "Setting default bunker return value");
-                                        if (returnType->isIntegerTy()) {
-                                            bunkerRetVal = ConstantInt::get(returnType, 0);
-                                        } else if (returnType->isPointerTy()) {
-                                            bunkerRetVal = ConstantPointerNull::get(cast<PointerType>(returnType));
-                                        } else if (returnType->isFloatingPointTy()) {
-                                            bunkerRetVal = ConstantFP::get(returnType, 0.0);
-                                        } else {
-                                            bunkerRetVal = UndefValue::get(returnType);
-                                        }
-                                    } else if (bunkerRetVal->getType() != returnType) {
-                                        LOG_DEBUG("performCodeFusion", "Casting bunker return value to {0}", getReadableTypeName(returnType));
-                                        bunkerRetVal = Builder.CreateBitCast(bunkerRetVal, returnType);
-                                    }
-                                    
-                                    ReturnInst* NewRI = ReturnInst::Create(M.getContext(), bunkerRetVal);
-                                    ReplaceInstWithInst(RI, NewRI);
-                                    
-                                    LOG_DEBUG("performCodeFusion", 
-                                        "Updated bunker return in block {0} with value type {1}",
-                                        getNodeId(BB),
-                                        getReadableTypeName(bunkerRetVal->getType()));
-                                }else if (foundReturn) {
-                                    // 将返回指令之后的所有指令标记为待删除
-                                    toDelete.push_back(Inst);
-                                }
-                            }
-                            for (Instruction* I : toDelete) {
-                                LOG_DEBUG("performCodeFusion", 
-                                    "Removing extra instruction after return in block {0}: {1}",
-                                    getNodeId(BB),
-                                    I->getOpcodeName());
-                                I->eraseFromParent();
-                            }
-                        }
-                        // 处理 target 函数的返回指令
-                        for (auto& pair : targetBlockMap) {
-                            BasicBlock* BB = pair.first;
-
-                            LOG_DEBUG("performCodeFusion", "Processing target block: {0}", getNodeId(BB));
-
-                            if (!BB || BB->empty()) continue;
-
-                            std::vector<Instruction*> toDelete;  // 存储需要删除的指令
-                            bool foundReturn = false;
-
-                            for (BasicBlock::iterator I = BB->begin(); I != BB->end();) {
-                                Instruction* Inst = &*I;
-                                ++I;
-
-                                // 打印每条指令的信息
-                                std::string instStr;
-                                raw_string_ostream rso(instStr);
-                                Inst->print(rso);
-                                LOG_DEBUG("performCodeFusion", 
-                                    "Block {0} - Processing instruction: {1} (opcode: {2})", 
-                                    getNodeId(BB),
-                                    instStr,
-                                    Inst->getOpcodeName());
-
-                                if (ReturnInst* RI = dyn_cast<ReturnInst>(Inst)){
-                                    // 添加额外的安全检查
-                                    if (!RI->getParent()) continue;
-                                    foundReturn = true;
-                                    IRBuilder<> Builder(RI);
-                                    Value* targetRetVal = RI->getReturnValue();
-                                    // 先重映射返回值
-                                    // if (targetRetVal) {
-                                    //     LOG_DEBUG("performCodeFusion", "Mapping target return value");
-                                    //     targetRetVal = MapValue(targetRetVal, targetVMap);
-                                    // }
-                                    
-                                    if (!targetRetVal) {
-                                        LOG_DEBUG("performCodeFusion", "Setting default target return value");
-                                        if (returnType->isIntegerTy()) {
-                                            targetRetVal = ConstantInt::get(returnType, 0);
-                                        } else if (returnType->isPointerTy()) {
-                                            targetRetVal = ConstantPointerNull::get(cast<PointerType>(returnType));
-                                        } else if (returnType->isFloatingPointTy()) {
-                                            targetRetVal = ConstantFP::get(returnType, 0.0);
-                                        } else {
-                                            targetRetVal = UndefValue::get(returnType);
-                                        }
-                                    } else if (targetRetVal->getType() != returnType) {
-                                        LOG_DEBUG("performCodeFusion", "Casting target return value to {0}", getReadableTypeName(returnType));
-                                        targetRetVal = Builder.CreateBitCast(targetRetVal, returnType);
-                                    }
-                                    
-                                    ReturnInst* NewRI = ReturnInst::Create(M.getContext(), targetRetVal);
-                                    ReplaceInstWithInst(RI, NewRI);
-                                    LOG_DEBUG("performCodeFusion", 
-                                        "Updated target return in block {0} with value type {1}",
-                                        getNodeId(BB),
-                                        getReadableTypeName(targetRetVal->getType()));
-                                }else if (foundReturn) {
-                                    // 将返回指令之后的所有指令标记为待删除
-                                    toDelete.push_back(Inst);
-                                }
-                            }
-                            for (Instruction* I : toDelete) {
-                                LOG_DEBUG("performCodeFusion", 
-                                    "Removing extra instruction after return in block {0}: {1}",
-                                    getNodeId(BB),
-                                    I->getOpcodeName());
-                                I->eraseFromParent();
-                            }
-                        }
-                    }
-                } else {
-                    LOG_INFO("performCodeFusion", 
-                        "Fused function {0} has void return type", 
-                        fusedFunc->getName().str());
-                    
-                    // 处理 void 返回类型的情况
-                    for (auto& pair : bunkerBlockMap) {
-                        BasicBlock* BB = pair.first;
-                        if (!BB || BB->empty()) continue;
-
-                        std::vector<Instruction*> toDelete;  // 存储需要删除的指令
-                        bool foundReturn = false;
-                        
-                        for (BasicBlock::iterator I = BB->begin(); I != BB->end();) {
-                            Instruction* Inst = &*I;
-                            ++I;
-                            if (ReturnInst* RI = dyn_cast<ReturnInst>(Inst)){
-                                // 添加额外的安全检查
-                                if (!RI->getParent()) continue;
-                                foundReturn = true;
-                                LOG_DEBUG("performCodeFusion", 
-                                    "Converting bunker return instruction to void return in block: {0}", 
-                                    getNodeId(BB));
-                                    
-                                ReturnInst* NewRI = ReturnInst::Create(M.getContext(), nullptr, RI);
-                                ReplaceInstWithInst(RI, NewRI);
-                            }else if (foundReturn) {
-                                // 将返回指令之后的所有指令标记为待删除
-                                toDelete.push_back(Inst);
-                            }
-                        }
-                        for (Instruction* I : toDelete) {
-                            LOG_DEBUG("performCodeFusion", 
-                                "Removing extra instruction after return in block {0}: {1}",
-                                getNodeId(BB),
-                                I->getOpcodeName());
-                            I->eraseFromParent();
-                        }
-                    }
-                    
-                    for (auto& pair : targetBlockMap) {
-                        BasicBlock* BB = pair.first;
-                        if (!BB || BB->empty()) continue;
-
-                        std::vector<Instruction*> toDelete;  // 存储需要删除的指令
-                        bool foundReturn = false;
-                        
-                        for (BasicBlock::iterator I = BB->begin(); I != BB->end();) {
-                            Instruction* Inst = &*I;
-                            ++I;
-                            if (ReturnInst* RI = dyn_cast<ReturnInst>(Inst)){
-                                // 添加额外的安全检查
-                                if (!RI->getParent()) continue;
-                                foundReturn = true;
-                                LOG_DEBUG("performCodeFusion", 
-                                    "Converting target return instruction to void return in block: {0}", 
-                                    BB->getName().str());
-                                    
-                                ReturnInst* NewRI = ReturnInst::Create(M.getContext(), nullptr, RI);
-                                ReplaceInstWithInst(RI, NewRI);
-                            }else if (foundReturn) {
-                                // 将返回指令之后的所有指令标记为待删除
-                                toDelete.push_back(Inst);
-                            }
-                        }
-                        for (Instruction* I : toDelete) {
-                            LOG_DEBUG("performCodeFusion", 
-                                "Removing extra instruction after return in block {0}: {1}",
-                                getNodeId(BB),
-                                I->getOpcodeName());
-                            I->eraseFromParent();
-                        }
-                    }
-                }
-
-                // 添加新的日志打印代码
-                LOG_INFO("performCodeFusion", "Listing all instructions after return repairing in function: {0}", 
-                    fusedFunc->getName().str());
-                dumpControlFlowGraph(*fusedFunc);
-
-                // 更新调用点
-                std::vector<CallInst*> bunkerCalls;
-                std::vector<CallInst*> targetCalls;
-
-                // 收集所有调用点
-                for (auto& U : bunkerFunc->uses()) {
-                    if (CallInst* CI = dyn_cast<CallInst>(U.getUser())) {
-                        bunkerCalls.push_back(CI);
-                    }
-                }
-
-                for (auto& U : targetFunc->uses()) {
-                    if (CallInst* CI = dyn_cast<CallInst>(U.getUser())) {
-                        targetCalls.push_back(CI);
-                    }
-                }
-
-                for (CallInst* CI : bunkerCalls) {
-                    updateCallSite(CI, fusedFunc, bunkerFunc, targetFunc, false);
-                }
-
-                for (CallInst* CI : targetCalls) {
-                    updateCallSite(CI, fusedFunc, targetFunc, bunkerFunc, true);
-                }
-                
-                // 删除原始函数
-                bunkerFunc->eraseFromParent();
-                targetFunc->eraseFromParent();
-
-
-                // 添加新的日志打印代码
-                LOG_INFO("performCodeFusion", "Listing all instructions after update calls in function: {0}", 
-                    fusedFunc->getName().str());
-                dumpControlFlowGraph(*fusedFunc);
-
-                
-                LOG_INFO("performCodeFusion", 
-                    "Completed function fusion: {0}", 
-                    fusedFunc->getName().str());
-            }
-            
-            LOG_INFO("performCodeFusion", 
-                "Code fusion completed, processed {0} function pairs", 
-                fusionPairs.size());
-        }
     };
 }
 

+ 0 - 409
src/SliceFusionPass.cpp

@@ -1,409 +0,0 @@
-#include "llvm/Pass.h"
-#include "llvm/IR/Function.h"
-#include "llvm/IR/BasicBlock.h"
-#include "llvm/IR/Instructions.h"
-#include "llvm/IR/LegacyPassManager.h"
-#include "llvm/Transforms/IPO/PassManagerBuilder.h"
-#include "llvm/Support/raw_ostream.h"
-#include "llvm/Analysis/CFG.h"
-#include "LogSystem.h"
-#include <vector>
-#include <map>
-#include <set>
-#include <queue>
-#include <algorithm>
-#include <string>
-
-using namespace llvm;
-
-namespace
-{
-    struct CodeFusionPass : public FunctionPass
-    {
-    public:
-        static char ID;
-        CodeFusionPass() : FunctionPass(ID) {}
-
-        bool runOnFunction(Function &F) override
-        {
-            // 配置日志系统
-            auto& logger = logging::LogSystem::getInstance();
-            logger.setGlobalLevel(logging::LogLevel::DEBUG);
-            logger.setContextFunction(F.getName().str());
-            // 配置Function输出权限
-            logger.enableFunction("checkCriticalPoint");
-            // logger.enableFunction("dumpControlFlowGraph");
-            // logger.enableFunction("isTargetCode");
-            LOG_INFO("runOnFunction", "Starting analysis for function: {0}", F.getName().str());
-
-            if(isTargetCode(F)){
-                for (BasicBlock &BB : F) {
-                    if(checkCriticalPoint(&BB)){
-                        criticalPoints.insert(&BB);
-                    }
-                }
-            }
-
-            // 绘制控制流图
-            // dumpControlFlowGraph(F);
-            
-            // 主要的混淆逻辑在这里实现
-            // analyzeFunction(F);
-            // selectFusionPoints(F);
-            // sliceTargetCode(F);
-            // fuseCode(F);
-            return true;
-        }
-
-    private:
-        std::set<BasicBlock*> criticalPoints;
-        std::vector<BasicBlock *> fusionPoints;
-        std::vector<std::vector<BasicBlock *>> targetSlices;
-
-        bool isTargetCode(Function &Func) {
-            LOG_INFO("isTargetCode", "Checking if function '{0}' is target code", Func.getName().str());
-            if (MDNode *MD = Func.getMetadata("project_source")) {
-                if (MDString *ProjectStr = dyn_cast<MDString>(MD->getOperand(0))) {
-                    std::string projectName = ProjectStr->getString().str();
-                    bool isTarget = (projectName == "Target");
-                    
-                    LOG_INFO("isTargetCode", "Function '{0}' project: {1}, isTarget: {2}", 
-                        Func.getName().str(), projectName, isTarget ? "true" : "false");
-                    
-                    return isTarget;
-                }
-            } 
-            if (!Func.isDeclaration()) {
-                LOG_WARNING("isTargetCode", "Function '{0}' has no project metadata, considering as non-target", 
-                    Func.getName().str());
-            }
-            return false;
-        }
-
-        std::string getNodeId(BasicBlock *BB){
-            std::string nodeId;
-            raw_string_ostream idOS(nodeId);
-            BB->printAsOperand(idOS, false);
-            idOS.flush();
-            return nodeId;
-        }
-
-        bool checkCriticalPoint(BasicBlock *BB) {
-            LOG_DEBUG("checkCriticalPoint", "Starting critical point check: {0}", getNodeId(BB));
-            if (!BB) {
-                LOG_ERROR("checkCriticalPoint", "Null basic block provided");
-                return false;
-            }
-            
-            Function *F = BB->getParent();
-            if (!F) {
-                LOG_ERROR("checkCriticalPoint", "Cannot get parent function for block");
-                return false;
-            }
-
-            // 获取起始和终止基本块
-            BasicBlock *Entry = &F->getEntryBlock();
-            BasicBlock *Exit = nullptr;
-            for (BasicBlock &B : *F) {
-                if (isa<ReturnInst>(B.getTerminator()) || 
-                    isa<UnreachableInst>(B.getTerminator())) {
-                    Exit = &B;
-                    break;
-                }
-            }
-            if (!Exit) {
-                LOG_WARNING("checkCriticalPoint", "No exit block found in function");
-                return false;
-            }
-
-            // 存储已访问的节点
-            std::set<BasicBlock*> visitedWithoutCurrent;
-            
-            // 不经过当前基本块的遍历函数
-            std::function<bool(BasicBlock*, BasicBlock*)> canReachExitWithout;
-            canReachExitWithout = [&canReachExitWithout, &visitedWithoutCurrent, BB]
-                (BasicBlock *Start, BasicBlock *Target) -> bool {
-                    if (Start == BB) return false;
-                    if (Start == Target) return true;
-                    
-                    if (visitedWithoutCurrent.count(Start)) return false;
-                    visitedWithoutCurrent.insert(Start);
-
-                    for (BasicBlock *Succ : successors(Start)) {
-                        if (canReachExitWithout(Succ, Target)) {
-                            return true;
-                        }
-                    }
-                    return false;
-                };
-
-            // 输出块的基本信息
-            LOG_TRACE("checkCriticalPoint", "Analyzing block: {0}", getNodeId(BB));
-            LOG_TRACE("checkCriticalPoint", "  Predecessors: {0}, Successors: {1}", 
-                pred_size(BB), succ_size(BB));
-
-            // 列出前驱基本块
-            LOG_TRACE("checkCriticalPoint", "Predecessor blocks:");
-            for (BasicBlock *Pred : predecessors(BB)) {
-                LOG_TRACE("checkCriticalPoint", "    {0}", getNodeId(Pred));
-            }
-
-            // 列出后继基本块
-            LOG_TRACE("checkCriticalPoint", "Successor blocks:");
-            for (BasicBlock *Succ : successors(BB)) {
-                LOG_TRACE("checkCriticalPoint", "    {0}", getNodeId(Succ));
-            }
-
-            // 清空访问集合
-            visitedWithoutCurrent.clear();
-            
-            // 判断从入口到出口是否必须经过当前基本块
-            bool isCritical = !canReachExitWithout(Entry, Exit);
-            
-            LOG_DEBUG("checkCriticalPoint", "Block {0} critical status: {1}", 
-                BB->getName().str(), isCritical ? "yes" : "no");
-            
-            return isCritical;
-        }
-
-        void dumpControlFlowGraph(Function &F) {
-            LOG_INFO("dumpControlFlowGraph", "Generating control flow graph for function: {0}", 
-                F.getName().str());
-            
-            if (F.empty()) {
-                LOG_WARNING("dumpControlFlowGraph", "Function is empty!");
-                return;
-            }
-
-            LOG_INFO("dumpControlFlowGraph", "Starting Mermaid graph generation");
-            errs() << "```mermaid\n";
-            errs() << "graph TD\n";
-            
-            // 为所有基本块创建节点
-            for (BasicBlock &BB : F) {
-                // 获取基本块的ID
-                std::string nodeId = getNodeId(&BB);
-                
-                if (!nodeId.empty() && nodeId[0] == '%') {
-                    nodeId = nodeId.substr(1);
-                }
-                
-                // 清理节点ID中的特殊字符
-                std::replace(nodeId.begin(), nodeId.end(), '.', '_');
-                std::replace(nodeId.begin(), nodeId.end(), ' ', '_');
-                std::replace(nodeId.begin(), nodeId.end(), '%', '_');
-                std::replace(nodeId.begin(), nodeId.end(), '-', '_');
-
-                LOG_TRACE("dumpControlFlowGraph", "Processing block with ID: {0}", nodeId);
-
-                // 构建基本块内容字符串
-                std::string blockContent;
-                raw_string_ostream contentOS(blockContent);
-                
-                // 添加基本块标签
-                contentOS << "Block " << nodeId << ":\\n";
-                
-                // 添加基本块中的每条指令
-                for (Instruction &I : BB) {
-                    std::string instStr;
-                    raw_string_ostream instOS(instStr);
-                    I.print(instOS);
-                    instOS.flush();
-                    
-                    // 清理指令字符串
-                    std::replace(instStr.begin(), instStr.end(), '"', '\'');
-                    std::replace(instStr.begin(), instStr.end(), '\n', ' ');
-                    
-                    // 如果指令太长,截断它
-                    if (instStr.length() > 50) {
-                        LOG_TRACE("dumpControlFlowGraph", "Truncating long instruction in block {0}", nodeId);
-                        instStr = instStr.substr(0, 47) + "...";
-                    }
-                    
-                    contentOS << instStr << "\\n";
-                }
-                contentOS.flush();
-
-                // 生成节点
-                if (criticalPoints.count(&BB)) {
-                    LOG_TRACE("dumpControlFlowGraph", "Marking block {0} as critical", nodeId);
-                    errs() << "    " << nodeId << "[\"" << blockContent << "\"]:::critical\n";
-                } else {
-                    errs() << "    " << nodeId << "[\"" << blockContent << "\"]\n";
-                }
-
-                // 处理边
-                for (BasicBlock *Succ : successors(&BB)) {
-                    std::string succId;
-                    raw_string_ostream succOS(succId);
-                    Succ->printAsOperand(succOS, false);
-                    succOS.flush();
-                    
-                    if (!succId.empty() && succId[0] == '%') {
-                        succId = succId.substr(1);
-                    }
-                    
-                    std::replace(succId.begin(), succId.end(), '.', '_');
-                    std::replace(succId.begin(), succId.end(), ' ', '_');
-                    std::replace(succId.begin(), succId.end(), '%', '_');
-                    std::replace(succId.begin(), succId.end(), '-', '_');
-
-                    LOG_TRACE("dumpControlFlowGraph", "Processing edge from {0} to {1}", nodeId, succId);
-
-                    // 检查分支类型并添加边
-                    if (BranchInst *BI = dyn_cast<BranchInst>(BB.getTerminator())) {
-                        if (BI->isConditional()) {
-                            // 获取条件表达式
-                            std::string condStr;
-                            raw_string_ostream condOS(condStr);
-                            BI->getCondition()->print(condOS);
-                            condOS.flush();
-                            
-                            bool isTrue = BI->getSuccessor(0) == Succ;
-                            LOG_TRACE("dumpControlFlowGraph", "Adding conditional branch edge: {0}", 
-                                isTrue ? "true" : "false");
-                            errs() << "    " << nodeId << " -->|" 
-                                << (isTrue ? "true" : "false") << "| " 
-                                << succId << "\n";
-                        } else {
-                            errs() << "    " << nodeId << " --> " << succId << "\n";
-                        }
-                    } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB.getTerminator())) {
-                        // 处理switch指令
-                        if (Succ == SI->getDefaultDest()) {
-                            LOG_TRACE("dumpControlFlowGraph", "Adding switch default edge");
-                            errs() << "    " << nodeId << " -->|default| " << succId << "\n";
-                        } else {
-                            for (auto Case : SI->cases()) {
-                                if (Case.getCaseSuccessor() == Succ) {
-                                    std::string caseStr;
-                                    raw_string_ostream caseOS(caseStr);
-                                    Case.getCaseValue()->print(caseOS);
-                                    LOG_TRACE("dumpControlFlowGraph", "Adding switch case edge: {0}", 
-                                        caseStr);
-                                    errs() << "    " << nodeId << " -->|case " 
-                                        << caseStr << "| " << succId << "\n";
-                                }
-                            }
-                        }
-                    } else {
-                        errs() << "    " << nodeId << " --> " << succId << "\n";
-                    }
-                }
-            }
-            
-            errs() << "    classDef critical fill:#f96,stroke:#333,stroke-width:4px\n";
-            errs() << "```\n";
-            LOG_INFO("dumpControlFlowGraph", "Completed graph generation");
-        }
-
-        void analyzeFunction(Function &F)
-        {
-            for (BasicBlock &BB : F)
-            {
-                for (Instruction &I : BB)
-                {
-                    if (CallInst *CI = dyn_cast<CallInst>(&I))
-                    {
-                        // 分析函数调用
-                        Function *CalledF = CI->getCalledFunction();
-                        if (CalledF && CalledF->isDeclaration())
-                        {
-                            errs() << "External function call: " << CalledF->getName() << "\n";
-                            // 这里可以添加区分变量
-                        }
-                    }
-                    // 可以添加更多的分析,如全局变量访问等
-                }
-            }
-        }
-
-        void selectFusionPoints(Function &F) {
-            errs() << "\n=== Starting Fusion Points Selection for function: " 
-                << F.getName() << " ===\n";
-            
-            fusionPoints.clear();
-            criticalPoints.clear();
-            
-            std::set<BasicBlock*> visited;
-            
-            // 首先收集所有可能的关键点
-            for (BasicBlock &BB : F) {
-                if (checkCriticalPoint(&BB)) {
-                    criticalPoints.insert(&BB);
-                }
-            }
-            
-            errs() << "\nIdentified " << criticalPoints.size() << " potential critical points\n";
-            
-            // 按照支配关系排序关键点
-            std::vector<BasicBlock*> orderedPoints;
-            BasicBlock *entryBlock = &F.getEntryBlock();
-            std::vector<BasicBlock*> workList;
-            workList.push_back(entryBlock);
-            
-            while (!workList.empty()) {
-                BasicBlock *current = workList.back();
-                workList.pop_back();
-                
-                if (visited.count(current))
-                    continue;
-                    
-                visited.insert(current);
-                
-                if (criticalPoints.count(current)) {
-                    orderedPoints.push_back(current);
-                    errs() << "Adding ordered critical point: " << current->getName() << "\n";
-                }
-                
-                for (BasicBlock *succ : successors(current)) {
-                    if (!visited.count(succ)) {
-                        workList.push_back(succ);
-                    }
-                }
-            }
-            
-            fusionPoints = orderedPoints;
-            
-            errs() << "\nSelected " << fusionPoints.size() << " fusion points in order:\n";
-            for (BasicBlock *BB : fusionPoints) {
-                errs() << "  " << BB->getName() << "\n";
-            }
-            
-            errs() << "\nValidating fusion points:\n";
-            for (size_t i = 0; i < fusionPoints.size(); ++i) {
-                BasicBlock *current = fusionPoints[i];
-                errs() << "Fusion point " << i << ": " << current->getName() << "\n";
-                
-                errs() << "Instructions in this fusion point:\n";
-                for (Instruction &I : *current) {
-                    errs() << "  " << I << "\n";
-                }
-                
-                if (i < fusionPoints.size() - 1) {
-                    BasicBlock *next = fusionPoints[i + 1];
-                    errs() << "Distance to next fusion point: " 
-                        << std::distance(current->getIterator(), next->getIterator()) 
-                        << " blocks\n";
-                }
-            }
-            
-            errs() << "=== Finished Fusion Points Selection ===\n\n";
-        }
-
-        void sliceTargetCode(Function &F)
-        {
-            errs() << "Slicing target code\n";
-            // 目标代码分片逻辑
-        }
-
-        void fuseCode(Function &F)
-        {
-            errs() << "Fusing code\n";
-            // 代码融合逻辑
-        }
-    };
-}
-
-char CodeFusionPass::ID = 0;
-static RegisterPass<CodeFusionPass> X("codefusion", "Code Fusion Pass");

+ 319 - 0
src/Util/CallGraphManager.cpp

@@ -0,0 +1,319 @@
+#include "llvm/Support/raw_ostream.h"
+
+#include "CallGraphManager.h"
+#include "LogSystem.h"
+#include "Utils.h"
+
+#include <queue>
+#include <algorithm>
+
+using namespace llvm;
+
+extern logging::LogSystem logger;
+
+/**
+ * @brief 构建调用图
+ * @param M LLVM模块
+ * @param targetFunctions 目标函数集合
+ * 
+ * 该函数遍历模块中的所有函数,建立函数间的调用关系图。
+ * 包含两个主要步骤:
+ * 1. 初始化所有非声明函数的节点
+ * 2. 建立函数间的调用关系
+ */
+void CallGraphManager::buildCallGraph(Module &M, const std::set<std::string> &targetFunctions) {
+    auto& logger = logging::LogSystem::getInstance();
+    logger.enableFunction("buildCallGraph");
+    LOG_INFO("buildCallGraph", "Building complete call graph");
+    // 初始化所有函数节点
+    for (Function &F : M) {
+        if (!F.isDeclaration()) {
+            std::string fname = F.getName().str();
+            bool isTarget = isTargetCode(F);
+            callGraph[fname] = CallNode(fname, isTarget);
+        }
+    }
+    // 建立调用关系
+    for (Function &F : M) {
+        if (!F.isDeclaration()) {
+            std::string callerName = F.getName().str();
+            for (BasicBlock &BB : F) {
+                for (Instruction &I : BB) {
+                    if (CallInst *CI = dyn_cast<CallInst>(&I)) {
+                        Function *CalledF = CI->getCalledFunction();
+                        if (CalledF && !CalledF->isDeclaration()) {
+                            std::string calleeName = CalledF->getName().str();
+                            callGraph[callerName].callees.insert(calleeName);
+                            callGraph[calleeName].callers.insert(callerName);
+                        }
+                    }
+                }
+            }
+        }
+    }
+    LOG_INFO("buildCallGraph", "Finished Building complete call graph");
+}
+
+/**
+ * @brief 生成项目调用图的Mermaid格式可视化
+ * 
+ * 该函数将调用图转换为Mermaid图表格式,包括:
+ * - 显示所有函数节点及其关键点数量
+ * - 标记目标函数(使用特殊样式)
+ * - 展示函数间的调用关系
+ */
+void CallGraphManager::generateProjectCallGraph() {
+    auto& logger = logging::LogSystem::getInstance();
+    logger.enableFunction("generateProjectCallGraph");
+    LOG_INFO("generateProjectCallGraph", "Generating project call graph");
+    errs() << "```mermaid\n";
+    errs() << "graph TD\n";
+    errs() << "    %% Project Call Graph\n";
+    
+    for (const auto &pair : callGraph) {
+        const std::string &name = pair.first;
+        const CallNode &node = pair.second;
+        std::string nodeId = sanitizeNodeId(name);
+        std::string criticalPoints = std::to_string(node.criticalPoints.size());
+        std::string style = node.isTarget ? ":::target" : "";
+        errs() << "    " << nodeId << "[\"" << name 
+            << "\\nCritical Points: " << criticalPoints
+            << "\"]" << style << "\n";
+    }
+    
+    for (const auto &pair : callGraph) {
+        const std::string &name = pair.first;
+        const CallNode &node = pair.second;
+        std::string callerId = sanitizeNodeId(name);
+        for (const auto &callee : node.callees) {
+            std::string calleeId = sanitizeNodeId(callee);
+            errs() << "    " << callerId << " --> " << calleeId << "\n";
+        }
+    }
+    errs() << "    classDef target fill:#f96,stroke:#333,stroke-width:4px\n";
+    errs() << "```\n\n";
+    LOG_INFO("generateProjectCallGraph", "Finished generating project call graph");
+}
+
+/**
+ * @brief 清理节点ID,使其符合Mermaid图表要求
+ * @param name 原始函数名
+ * @return 处理后的节点ID
+ * 
+ * 处理步骤:
+ * 1. 移除前导%符号
+ * 2. 替换特殊字符为下划线
+ * 3. 确保ID以字母开头
+ */
+std::string CallGraphManager::sanitizeNodeId(const std::string &name) {
+    std::string id = name;
+    // 移除前导 %
+    if (!id.empty() && id[0] == '%') {
+        id = id.substr(1);
+    }
+    
+    // 替换非法字符
+    std::replace(id.begin(), id.end(), '.', '_');
+    std::replace(id.begin(), id.end(), ' ', '_');
+    std::replace(id.begin(), id.end(), '-', '_');
+    std::replace(id.begin(), id.end(), '%', '_');
+    
+    // 确保ID以字母开头
+    if (!id.empty() && std::isdigit(id[0])) {
+        id = "block_" + id;
+    }
+    
+    return id;
+}
+
+/**
+ * @brief 生成并输出函数的控制流图
+ * @param F 要分析的函数
+ * 
+ * 该函数生成Mermaid格式的控制流图,包括:
+ * - 显示基本块的内容和指令
+ * - 标记关键点基本块
+ * - 展示条件分支和跳转关系
+ * - 支持条件分支、switch语句等不同类型的控制流
+ */
+void CallGraphManager::dumpControlFlowGraph(Function &F) {
+    // auto& logger = logging::LogSystem::getInstance();
+    // logger.enableFunction("dumpControlFlowGraph");
+    LOG_INFO("dumpControlFlowGraph", "Generating control flow graph for function: {0}", 
+        F.getName().str());
+    
+    if (F.empty()) {
+        LOG_WARNING("dumpControlFlowGraph", "Function is empty!");
+        return;
+    }
+
+    LOG_INFO("dumpControlFlowGraph", "Starting Mermaid graph generation");
+    errs() << "```mermaid: " << F.getName().str() << "\n";
+    errs() << "graph TD\n";
+    
+    for (BasicBlock &BB : F) {
+        std::string nodeId = getNodeId(&BB);
+        if (!nodeId.empty() && nodeId[0] == '%') {
+            nodeId = nodeId.substr(1);
+        }
+        std::replace(nodeId.begin(), nodeId.end(), '.', '_');
+        std::replace(nodeId.begin(), nodeId.end(), ' ', '_');
+        std::replace(nodeId.begin(), nodeId.end(), '%', '_');
+        std::replace(nodeId.begin(), nodeId.end(), '-', '_');
+
+        LOG_TRACE("dumpControlFlowGraph", "Processing block with ID: {0}", nodeId);
+
+        std::string blockContent;
+        raw_string_ostream contentOS(blockContent);
+        
+        contentOS << "Block " << nodeId << ":\\n";
+        
+        for (Instruction &I : BB) {
+            std::string instStr;
+            raw_string_ostream instOS(instStr);
+            I.print(instOS);
+            instOS.flush();
+            
+            std::replace(instStr.begin(), instStr.end(), '"', '\'');
+            std::replace(instStr.begin(), instStr.end(), '\n', ' ');
+            
+            contentOS << instStr << "\\n";
+        }
+        contentOS.flush();
+
+        std::string fname = F.getName().str();
+
+        if (callGraph[fname].criticalPoints.count(&BB)) {
+            LOG_TRACE("dumpControlFlowGraph", "Marking block {0} as critical", nodeId);
+            errs() << "    " << nodeId << "[\"" << blockContent << "\"]:::critical\n";
+        } else {
+            errs() << "    " << nodeId << "[\"" << blockContent << "\"]\n";
+        }
+
+        for (BasicBlock *Succ : successors(&BB)) {
+            std::string succId;
+            raw_string_ostream succOS(succId);
+            Succ->printAsOperand(succOS, false);
+            succOS.flush();
+            
+            if (!succId.empty() && succId[0] == '%') {
+                succId = succId.substr(1);
+            }
+            
+            std::replace(succId.begin(), succId.end(), '.', '_');
+            std::replace(succId.begin(), succId.end(), ' ', '_');
+            std::replace(succId.begin(), succId.end(), '%', '_');
+            std::replace(succId.begin(), succId.end(), '-', '_');
+
+            LOG_TRACE("dumpControlFlowGraph", "Processing edge from {0} to {1}", nodeId, succId);
+
+            if (BranchInst *BI = dyn_cast<BranchInst>(BB.getTerminator())) {
+                if (BI->isConditional()) {
+                    std::string condStr;
+                    raw_string_ostream condOS(condStr);
+                    BI->getCondition()->print(condOS);
+                    condOS.flush();
+                    bool isTrue = BI->getSuccessor(0) == Succ;
+                    LOG_TRACE("dumpControlFlowGraph", "Adding conditional branch edge: {0}", 
+                        isTrue ? "true" : "false");
+                    errs() << "    " << nodeId << " -->|" 
+                        << (isTrue ? "true" : "false") << "| " 
+                        << succId << "\n";
+                } else {
+                    errs() << "    " << nodeId << " --> " << succId << "\n";
+                }
+            } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB.getTerminator())) {
+                if (Succ == SI->getDefaultDest()) {
+                    LOG_TRACE("dumpControlFlowGraph", "Adding switch default edge");
+                    errs() << "    " << nodeId << " -->|default| " << succId << "\n";
+                } else {
+                    for (auto Case : SI->cases()) {
+                        if (Case.getCaseSuccessor() == Succ) {
+                            std::string caseStr;
+                            raw_string_ostream caseOS(caseStr);
+                            Case.getCaseValue()->print(caseOS);
+                            LOG_TRACE("dumpControlFlowGraph", "Adding switch case edge: {0}", 
+                                caseStr);
+                            errs() << "    " << nodeId << " -->|case " 
+                                << caseStr << "| " << succId << "\n";
+                        }
+                    }
+                }
+            } else {
+                errs() << "    " << nodeId << " --> " << succId << "\n";
+            }
+        }
+    }
+    errs() << "    classDef critical fill:#f96,stroke:#333,stroke-width:4px\n";
+    errs() << "```\n";
+    LOG_INFO("dumpControlFlowGraph", "Completed graph generation");
+}
+
+/**
+ * @brief 生成融合匹配的可视化图
+ * @param targetFunctions 目标函数集合
+ * @param bunkerFunctions 堡垒函数集合
+ * @param fusionPairs 融合配对关系
+ * 
+ * 生成Mermaid格式的图表,展示:
+ * - 左侧:目标项目函数(包含切片数量)
+ * - 右侧:堡垒项目函数(包含关键点数量)
+ * - 函数间的融合匹配关系
+ */
+void CallGraphManager::generateFusionMatchGraph(
+    const std::set<std::string>& targetFunctions,
+    const std::set<std::string>& bunkerFunctions,
+    const std::map<std::string, std::string>& fusionPairs) {
+    
+    LOG_INFO("generateFusionMatchGraph", "Generating fusion match visualization");
+    
+    errs() << "```mermaid\n";
+    errs() << "graph LR\n";
+    errs() << "    %% Fusion Match Graph\n";
+    errs() << "    %% Left side: Target Project, Right side: Bunker Project\n\n";
+    
+    errs() << "    subgraph Target[\"Target Project\"]\n";
+    errs() << "        direction TB\n";
+    for (const auto& targetFunc : targetFunctions) {
+        std::string nodeId = sanitizeNodeId(targetFunc);
+        std::string sliceNum = std::to_string(callGraph[targetFunc].slices_num);
+        errs() << "        " << nodeId << "[\"" << targetFunc 
+            << "\\nSliceNum: " << sliceNum
+            << "\"]:::target\n";
+    }
+    errs() << "    end\n\n";
+    
+    errs() << "    subgraph Bunker[\"Bunker Project\"]\n";
+    errs() << "        direction TB\n";
+    for (const auto& bunkerFunc : bunkerFunctions) {
+        std::string nodeId = sanitizeNodeId(bunkerFunc);
+        std::string criticalPoints = std::to_string(callGraph[bunkerFunc].criticalPoints.size());
+        errs() << "        " << nodeId << "[\"" << bunkerFunc 
+            << "\\nCritical Points: " << criticalPoints
+            << "\"]:::bunker\n";
+    }
+    errs() << "    end\n\n";
+    
+    errs() << "    %% Fusion Matches\n";
+    for (const auto& match : fusionPairs) {
+        std::string targetId = sanitizeNodeId(match.first);
+        std::string bunkerId = sanitizeNodeId(match.second);
+        errs() << "    " << targetId << " ==>|fusion| " << bunkerId << "\n";
+    }
+    
+    errs() << "    %% Styles\n";
+    errs() << "    classDef target fill:#f96,stroke:#333,stroke-width:2px\n";
+    errs() << "    classDef bunker fill:#9cf,stroke:#333,stroke-width:2px\n";
+    errs() << "    style Target fill:#fff,stroke:#f96,stroke-width:2px\n";
+    errs() << "    style Bunker fill:#fff,stroke:#9cf,stroke-width:2px\n";
+    
+    errs() << "```\n\n";
+    
+    LOG_INFO("generateFusionMatchGraph", 
+        "Generated visualization with {0} target functions and {1} bunker functions", 
+        targetFunctions.size(), 
+        bunkerFunctions.size());
+    LOG_INFO("generateFusionMatchGraph", 
+        "Total fusion matches: {0}", 
+        fusionPairs.size());
+}

+ 64 - 0
src/Util/CallGraphManager.h

@@ -0,0 +1,64 @@
+#ifndef CALL_GRAPH_H
+#define CALL_GRAPH_H
+
+#include "llvm/IR/Module.h"
+#include "llvm/IR/Function.h"
+#include "llvm/IR/BasicBlock.h"
+#include "llvm/IR/Instructions.h"
+#include "llvm/Support/raw_ostream.h"
+#include "llvm/Analysis/CFG.h"
+#include <string>
+#include <set>
+#include <map>
+#include <vector>
+
+namespace llvm {
+    struct Slice {
+        std::vector<BasicBlock*> blocks;
+    };
+
+    struct CallNode {
+        std::string name;
+        bool isTarget;
+        std::set<std::string> callers;
+        std::set<std::string> callees;
+        std::set<BasicBlock*> criticalPoints;
+        std::map<BasicBlock*, bool> isPredValid;  // true表示前驱可用
+        std::map<BasicBlock*, bool> isSuccValid;  // true表示后继可用
+        unsigned points_num;
+        unsigned slices_num;
+        unsigned depth;
+        std::vector<Slice> slices;
+        
+        CallNode() : name(""), isTarget(false), depth(0), points_num(0), slices_num(0) {}
+        CallNode(std::string n, bool target = false) 
+            : name(n), isTarget(target), depth(0), points_num(0), slices_num(0) {}
+    };
+
+    class CallGraphManager {
+    public:
+        CallGraphManager() = default;
+        
+        void buildCallGraph(Module &M, const std::set<std::string> &targetFunctions);
+        void calculateCallDepths(Module &M);
+        void generateProjectCallGraph();
+        void dumpControlFlowGraph(Function &F);
+        
+        std::map<std::string, CallNode>& getCallGraph() { return callGraph; }
+        std::map<std::string, unsigned>& getMaxCallDepths() { return maxCallDepths; }
+        void generateFusionMatchGraph(
+            const std::set<std::string>& targetFunctions,
+            const std::set<std::string>& bunkerFunctions,
+            const std::map<std::string, std::string>& fusionPairs);
+
+        CallNode& operator[](const std::string& name) { return callGraph[name]; }
+
+    private:
+        std::map<std::string, CallNode> callGraph;
+        std::map<std::string, unsigned> maxCallDepths;
+        
+        std::string sanitizeNodeId(const std::string &name);
+    };
+} // namespace llvm
+
+#endif // CALL_GRAPH_H

+ 45 - 0
src/Util/LogSystem.cpp

@@ -0,0 +1,45 @@
+#include "LogSystem.h"
+
+namespace logging {
+
+LogSystem& LogSystem::getInstance() {
+    static LogSystem instance;
+    return instance;
+}
+
+LogSystem::LogSystem() : globalLevel(LogLevel::INFO) {}
+
+void LogSystem::setGlobalLevel(LogLevel level) {
+    globalLevel = level;
+}
+
+void LogSystem::setFunctionLevel(const std::string& funcName, LogLevel level) {
+    functionLevels[funcName] = level;
+}
+
+void LogSystem::enableFunction(const std::string& funcName) {
+    enabledFunctions.insert(funcName);
+}
+
+void LogSystem::disableFunction(const std::string& funcName) {
+    enabledFunctions.erase(funcName);
+}
+
+void LogSystem::setContextFunction(const std::string& funcName) {
+    currentFunctionName = funcName;
+}
+
+bool LogSystem::shouldLog(const std::string& funcName, LogLevel level) {
+    if (enabledFunctions.find(funcName) == enabledFunctions.end()) {
+        return false;
+    }
+
+    auto it = functionLevels.find(funcName);
+    if (it != functionLevels.end()) {
+        return level >= it->second;
+    }
+
+    return level >= globalLevel;
+}
+
+} // namespace logging

+ 62 - 0
src/Util/LogSystem.h

@@ -0,0 +1,62 @@
+#ifndef LOG_SYSTEM_H
+#define LOG_SYSTEM_H
+
+#include "llvm/Support/raw_ostream.h"
+#include <string>
+#include <map>
+#include <set>
+#include <sstream>
+
+namespace logging {
+
+enum class LogLevel {
+    TRACE,
+    DEBUG,
+    INFO,
+    WARNING,
+    ERROR,
+    NONE
+};
+
+class LogSystem {
+public:
+    static LogSystem& getInstance();
+    void setGlobalLevel(LogLevel level);
+    void setFunctionLevel(const std::string& funcName, LogLevel level);
+    void enableFunction(const std::string& funcName);
+    void disableFunction(const std::string& funcName);
+    void setContextFunction(const std::string& funcName);
+    bool shouldLog(const std::string& funcName, LogLevel level);
+
+    template<typename... Args>
+    void log(const std::string& funcName, LogLevel level, const char* format, Args... args);
+
+private:
+    LogSystem();
+    LogLevel globalLevel;
+    std::map<std::string, LogLevel> functionLevels;
+    std::set<std::string> enabledFunctions;
+    std::string currentFunctionName;
+
+    void replaceAll(std::string&) {}
+
+    template<typename T, typename... Args>
+    void replaceAll(std::string& str, T&& value, Args&&... args);
+};
+
+#define LOG_TRACE(func, ...) \
+    logging::LogSystem::getInstance().log(func, logging::LogLevel::TRACE, __VA_ARGS__)
+#define LOG_DEBUG(func, ...) \
+    logging::LogSystem::getInstance().log(func, logging::LogLevel::DEBUG, __VA_ARGS__)
+#define LOG_INFO(func, ...) \
+    logging::LogSystem::getInstance().log(func, logging::LogLevel::INFO, __VA_ARGS__)
+#define LOG_WARNING(func, ...) \
+    logging::LogSystem::getInstance().log(func, logging::LogLevel::WARNING, __VA_ARGS__)
+#define LOG_ERROR(func, ...) \
+    logging::LogSystem::getInstance().log(func, logging::LogLevel::ERROR, __VA_ARGS__)
+
+} // namespace logging
+
+#include "LogSystem.inl"
+
+#endif // LOG_SYSTEM_H

+ 75 - 0
src/Util/LogSystem.inl

@@ -0,0 +1,75 @@
+#ifndef LOG_SYSTEM_INL
+#define LOG_SYSTEM_INL
+
+namespace logging {
+
+template<typename... Args>
+void LogSystem::log(const std::string& funcName, LogLevel level, const char* format, Args... args) {
+    if (!shouldLog(funcName, level)) {
+        return;
+    }
+
+    std::string levelStr;
+    switch (level) {
+        case LogLevel::TRACE:   levelStr = "TRACE"; break;
+        case LogLevel::DEBUG:   levelStr = "DEBUG"; break;
+        case LogLevel::INFO:    levelStr = "INFO"; break;
+        case LogLevel::WARNING: levelStr = "WARNING"; break;
+        case LogLevel::ERROR:   levelStr = "ERROR"; break;
+        default: return;
+    }
+
+    std::string msg(format);
+    replaceAll(msg, args...);
+
+    llvm::errs() << "[" << levelStr << "]";
+    if (!currentFunctionName.empty()) {
+        llvm::errs() << "[" << currentFunctionName << "]";
+    }
+    llvm::errs() << "[" << funcName << "] " << msg << "\n";
+}
+
+template<typename T, typename... Args>
+void LogSystem::replaceAll(std::string& str, T&& value, Args&&... args) {
+    std::stringstream ss;
+    ss << std::forward<T>(value);
+    size_t pos = str.find("{0}");
+    if (pos != std::string::npos) {
+        str.replace(pos, 3, ss.str());
+    }
+    
+    std::string rest = str;
+    size_t start = 0;
+    while ((pos = rest.find("{", start)) != std::string::npos) {
+        size_t end = rest.find("}", pos);
+        if (end != std::string::npos) {
+            std::string num = rest.substr(pos + 1, end - pos - 1);
+            
+            bool isValidNumber = true;
+            for (char c : num) {
+                if (!std::isdigit(c)) {
+                    isValidNumber = false;
+                    break;
+                }
+            }
+            
+            if (isValidNumber) {
+                int n = 0;
+                for (char c : num) {
+                    n = n * 10 + (c - '0');
+                }
+                
+                if (n > 0) {
+                    rest.replace(pos, end - pos + 1, "{" + std::to_string(n-1) + "}");
+                }
+            }
+        }
+        start = pos + 1;
+    }
+    str = rest;
+    replaceAll(str, std::forward<Args>(args)...);
+}
+
+} // namespace logging
+
+#endif // LOG_SYSTEM_INL

+ 23 - 0
src/Util/Utils.cpp

@@ -0,0 +1,23 @@
+#include "Util/Utils.h"
+#include "llvm/IR/Metadata.h"
+#include "llvm/Support/raw_ostream.h"
+
+namespace llvm {
+    bool isTargetCode(Function &F) {
+        if (MDNode *MD = F.getMetadata("project_source")) {
+            if (MDString *ProjectStr = dyn_cast<MDString>(MD->getOperand(0))) {
+                std::string projectName = ProjectStr->getString().str();
+                return (projectName == "Target");
+            }
+        }
+        return false;
+    }
+
+    std::string getNodeId(BasicBlock *BB) {
+        std::string nodeId;
+        raw_string_ostream idOS(nodeId);
+        BB->printAsOperand(idOS, false);
+        idOS.flush();
+        return nodeId;
+    }
+}

+ 11 - 0
src/Util/Utils.h

@@ -0,0 +1,11 @@
+#ifndef UTILS_H
+#define UTILS_H
+
+#include "llvm/IR/Function.h"
+
+namespace llvm {
+    bool isTargetCode(Function &F);
+    std::string getNodeId(BasicBlock *BB);
+}
+
+#endif // UTILS_H

Kaikkia tiedostoja ei voida näyttää, sillä liian monta tiedostoa muuttui tässä diffissä