=== FILE Task1_Control_FlowGraph.ipynb ===
=== CELL 0 ===
1: import os
2: import random
3: import openai
4: import pandas as pd
5: import os
6: 
7: # 设置环境变量
8: [REDACTED CREDENTIAL-RELATED LINE]
9: 
10: # 初始化 Groq 客户端
11: import os
12: from together import Together
13: 
14: [REDACTED CREDENTIAL-RELATED LINE]
=== CELL 1 ===
1: import os
2: from together import Together
3: [REDACTED CREDENTIAL-RELATED LINE]
4: [REDACTED CREDENTIAL-RELATED LINE]
5: client = Together()
6: 
7: response = client.chat.completions.create(
8:     model= "deepseek-ai/DeepSeek-R1-Distill-Llama-70B-free",
9:     messages=[{"role": "user", "content": "What are some fun things to do in New York?"}],
10: )
11: print(response.choices[0].message.content)
=== CELL 2 ===
1: def CFG_IR(file_content):
2:     
3:     prompt = f"""
4:         You are an control flow graph analyzer in Intermediate code. I will give you a IR code program and you give me the control flow graph. 
5:         
6:         Here is the IR code input:
7:         ```
8:         {file_content}
9:         ```
10:        Your task is to The output format is dot file including nodes and edges. Don't need to list the content of each basic blocks. Just show the title of each nodes.
11:        """
12:        
13:     response = client.chat.completions.create(
14:         model="deepseek-ai/DeepSeek-R1-Distill-Llama-70B-free",
15:         messages=[
16:             {"role": "system", "content": "You are an expert in high-performance computation."},
17:             {"role": "user", "content": prompt}
18:         ],
19:         #max_tokens=204800,
20:         temperature=0.7
21:             )
22:     analysis = response.choices[0].message.content.strip()
23:     print(analysis)
24:     return analysis   
=== CELL 3 ===
1: IR_code_example = """; ModuleID = 'test.c'
2: source_filename = "test.c"
3: target datalayout = "e-m:e-p270:32:32-p271:32:32-p272:64:64-i64:64-f80:128-n8:16:32:64-S128"
4: target triple = "x86_64-unknown-linux-gnu"
5: 
6: @.str = private unnamed_addr constant [4 x i8] c"f1\0A\00", align 1
7: @.str.1 = private unnamed_addr constant [4 x i8] c"f2\0A\00", align 1
8: @.str.2 = private unnamed_addr constant [4 x i8] c"f3\0A\00", align 1
9: @.str.3 = private unnamed_addr constant [14 x i8] c"hello world!\0A\00", align 1
10: 
11: ; Function Attrs: noinline nounwind optnone uwtable
12: define dso_local void @f1() #0 {
13:   %1 = call i32 (i8*, ...) @printf(i8* getelementptr inbounds ([4 x i8], [4 x i8]* @.str, i64 0, i64 0))
14:   ret void
15: }
16: 
17: declare dso_local i32 @printf(i8*, ...) #1
18: 
19: ; Function Attrs: noinline nounwind optnone uwtable
20: define dso_local void @f2() #0 {
21:   %1 = call i32 (i8*, ...) @printf(i8* getelementptr inbounds ([4 x i8], [4 x i8]* @.str.1, i64 0, i64 0))
22:   call void @f1()
23:   ret void
24: }
25: 
26: ; Function Attrs: noinline nounwind optnone uwtable
27: define dso_local void @ff3() #0 {
28:   %1 = alloca i32, align 4
29:   %2 = call i32 (i8*, ...) @printf(i8* getelementptr inbounds ([4 x i8], [4 x i8]* @.str.2, i64 0, i64 0))
30:   store i32 1, i32* %1, align 4
31:   %3 = load i32, i32* %1, align 4
32:   %4 = icmp eq i32 %3, 1
33:   br i1 %4, label %5, label %6
34: 
35: 5:                                                ; preds = %0
36:   call void @f1()
37:   br label %7
38: 
39: 6:                                                ; preds = %0
40:   call void @f2()
41:   br label %7
42: 
43: 7:                                                ; preds = %6, %5
44:   call void @f1()
45:   call void @f2()
46:   ret void
47: }
48: 
49: ; Function Attrs: noinline nounwind optnone uwtable
50: define dso_local i32 @main() #0 {
51:   %1 = alloca i32, align 4
52:   store i32 0, i32* %1, align 4
53:   %2 = call i32 (i8*, ...) @printf(i8* getelementptr inbounds ([14 x i8], [14 x i8]* @.str.3, i64 0, i64 0))
54:   call void @ff3()
55:   ret i32 0
56: }
57: attributes #0 = { noinline nounwind optnone uwtable "frame-pointer"="all" "min-legal-vector-width"="0" "no-trapping-math"="true" "stack-protector-buffer-size"="8" "target-cpu"="x86-64" "target-features"="+cx8,+fxsr,+mmx,+sse,+sse2,+x87" "tune-cpu"="generic" }
58: attributes #1 = { "frame-pointer"="all" "no-trapping-math"="true" "stack-protector-buffer-size"="8" "target-cpu"="x86-64" "target-features"="+cx8,+fxsr,+mmx,+sse,+sse2,+x87" "tune-cpu"="generic" }
59: 
60: !llvm.module.flags = !{!0, !1, !2}
61: !llvm.ident = !{!3}
62: 
63: !0 = !{i32 1, !"wchar_size", i32 4}
64: !1 = !{i32 7, !"uwtable", i32 1}
65: !2 = !{i32 7, !"frame-pointer", i32 2}
66: !3 = !{!"clang version 13.0.0 (https://github.com/llvm/llvm-project.git d7b669b3a30345cfcdb2fde2af6f48aa4b94845d)"}
67:  """
=== CELL 4 ===
1: CFG_IR(IR_code_example)
=== CELL 5 ===
1: def process_bc_file(file_path, output_dir):
2:     try:
3:         with open(file_path, 'rb') as file:
4:             file_content = file.read()
5:             print(f"Successfully read {file_path}")
6:             decompiled_code = CFG_IR(file_content)
7:             output_file_name = os.path.basename(file_path).replace('.bc', '.dot')
8:             output_file_path = os.path.join(output_dir, output_file_name)
9:             with open(output_file_path, 'w') as output_file:
10:                 output_file.write(decompiled_code)
11:             return len(file_content)
12:     except Exception as e:
13:         print(f"Error processing {file_path}: {e}")
14:         return None
=== CELL 6 ===
1: def read_and_process_all_directories(root_dir, output_dir):
2:     processed_files = 0
3:     failed_files = 0
4:     file_names = []
5:     token_lengths_list = []
6:     failed_file_names = []
7:     for subdir, _, files in os.walk(root_dir):
8:         for file in files:
9:             if file.endswith('.bc'):
10:                 file_path = os.path.join(subdir, file)
11:                 token_length = process_bc_file(file_path, output_dir)
12:                 if token_length is not None:
13:                     processed_files += 1
14:                     file_names.append(file)
15:                     token_lengths_list.append(token_length)
16:                 else:
17:                     failed_files += 1
18:                     failed_file_names.append(file)
19:     
20:     return processed_files, failed_files, file_names, failed_file_names,token_lengths_list
=== CELL 7 ===
1: root_directory = "/Users/jianfengzhu/Desktop/Researvh Work/02024AugLLMs_in_IRs/LLMs-in-IR-SEP7/processed_data/Human_x_164_O3"
2: #for test directory
3: #root_directory = "/Users/jianfengzhu/Desktop/LLMs/LLMs_Evaluation_IR/LLMs-in-IR-1/processed_data/CFG_LLM/counting_sort2"
4: output_directory = "/Users/jianfengzhu/Desktop/Researvh Work/02024AugLLMs_in_IRs/LLMs-in-IR-SEP7/processed_data/ScriptTest/DeepSeekFolder/DeepSeek_CFG_Result/Run3_DeepSeek_CFG"
5: # Ensure the output directory exists
6: os.makedirs(output_directory, exist_ok=True)
7: 
8: processed_files, failed_files, file_names,failed_file_names, token_lengths_list = read_and_process_all_directories(root_directory, output_directory)
9: # Print the statistics
10: print(f"Processed Files: {processed_files}")
11: print(f"Failed Files: {failed_files}")
12: # Print the names of failed files
13: if failed_files > 0:
14:     print("Failed file names:")
15:     for file in failed_file_names:
16:         print(file)
17: # Save the DataFrame to a CSV file
18: #csv_output_path = "/Users/jianfengzhu/Desktop/LLMs-in-IR-SEP7/processed_data/ControlFlowGraph_Humaneval_x_cpp164_result/CodeLlama_Humaneval_x_cpp_164/processed_files_statistics.csv"
19: #df.to_csv(csv_output_path, index=False)
20: #print(f"DataFrame saved to {csv_output_path}")
=== FILE Task2_Decompile.ipynb ===
=== CELL 0 ===
1: import os
2: import random
3: import openai
4: import pandas as pd
5: import os
6: 
7: # 设置环境变量
8: [REDACTED CREDENTIAL-RELATED LINE]
9: 
10: # 初始化 Groq 客户端
11: import os
12: from together import Together
13: 
14: [REDACTED CREDENTIAL-RELATED LINE]
=== CELL 1 ===
1: import os
2: from together import Together
3: [REDACTED CREDENTIAL-RELATED LINE]
4: [REDACTED CREDENTIAL-RELATED LINE]
5: client = Together()
6: 
7: response = client.chat.completions.create(
8:     model= "deepseek-ai/DeepSeek-R1-Distill-Llama-70B-free",
9:     messages=[{"role": "user", "content": "What are some fun things to do in New York?"}],
10: )
11: print(response.choices[0].message.content)
=== CELL 2 ===
1: import openai
2: def Decompiling_IR(file_content):
3:     
4:     prompt = f"""
5:         You are an expert in high-performance computation. I will provide you with LLVM IR (Intermediate Representation) code, 
6:         which is a low-level, platform-independent representation of a program. 
7:         
8:        Here is the IR code input:
9:         ```
10:         {file_content}
11:         ```
12:         Your task is to decompile the file_content to C or C++ source code format, which I can run it directly. 
13:         """        
14:     response = client.chat.completions.create(
15:         model="deepseek-ai/DeepSeek-R1-Distill-Llama-70B-free",
16:             messages=[{
17:                 "role": "user", 
18:                 "content": prompt,
19:             }
20:         ],
21:         temperature=0.7
22:             )
23:     analysis = response.choices[0].message.content.strip()
24:     print(analysis)
25:     return analysis
26:     
=== CELL 3 ===
1: IR_code_example = """; ModuleID = 'test.c'
2: source_filename = "test.c"
3: target datalayout = "e-m:e-p270:32:32-p271:32:32-p272:64:64-i64:64-f80:128-n8:16:32:64-S128"
4: target triple = "x86_64-unknown-linux-gnu"
5: 
6: @.str = private unnamed_addr constant [4 x i8] c"f1\0A\00", align 1
7: @.str.1 = private unnamed_addr constant [4 x i8] c"f2\0A\00", align 1
8: @.str.2 = private unnamed_addr constant [4 x i8] c"f3\0A\00", align 1
9: @.str.3 = private unnamed_addr constant [14 x i8] c"hello world!\0A\00", align 1
10: 
11: ; Function Attrs: noinline nounwind optnone uwtable
12: define dso_local void @f1() #0 {
13:   %1 = call i32 (i8*, ...) @printf(i8* getelementptr inbounds ([4 x i8], [4 x i8]* @.str, i64 0, i64 0))
14:   ret void
15: }
16: 
17: declare dso_local i32 @printf(i8*, ...) #1
18: 
19: ; Function Attrs: noinline nounwind optnone uwtable
20: define dso_local void @f2() #0 {
21:   %1 = call i32 (i8*, ...) @printf(i8* getelementptr inbounds ([4 x i8], [4 x i8]* @.str.1, i64 0, i64 0))
22:   call void @f1()
23:   ret void
24: }
25: 
26: ; Function Attrs: noinline nounwind optnone uwtable
27: define dso_local void @ff3() #0 {
28:   %1 = alloca i32, align 4
29:   %2 = call i32 (i8*, ...) @printf(i8* getelementptr inbounds ([4 x i8], [4 x i8]* @.str.2, i64 0, i64 0))
30:   store i32 1, i32* %1, align 4
31:   %3 = load i32, i32* %1, align 4
32:   %4 = icmp eq i32 %3, 1
33:   br i1 %4, label %5, label %6
34: 
35: 5:                                                ; preds = %0
36:   call void @f1()
37:   br label %7
38: 
39: 6:                                                ; preds = %0
40:   call void @f2()
41:   br label %7
42: 
43: 7:                                                ; preds = %6, %5
44:   call void @f1()
45:   call void @f2()
46:   ret void
47: }
48: 
49: ; Function Attrs: noinline nounwind optnone uwtable
50: define dso_local i32 @main() #0 {
51:   %1 = alloca i32, align 4
52:   store i32 0, i32* %1, align 4
53:   %2 = call i32 (i8*, ...) @printf(i8* getelementptr inbounds ([14 x i8], [14 x i8]* @.str.3, i64 0, i64 0))
54:   call void @ff3()
55:   ret i32 0
56: }
57: attributes #0 = { noinline nounwind optnone uwtable "frame-pointer"="all" "min-legal-vector-width"="0" "no-trapping-math"="true" "stack-protector-buffer-size"="8" "target-cpu"="x86-64" "target-features"="+cx8,+fxsr,+mmx,+sse,+sse2,+x87" "tune-cpu"="generic" }
58: attributes #1 = { "frame-pointer"="all" "no-trapping-math"="true" "stack-protector-buffer-size"="8" "target-cpu"="x86-64" "target-features"="+cx8,+fxsr,+mmx,+sse,+sse2,+x87" "tune-cpu"="generic" }
59: 
60: !llvm.module.flags = !{!0, !1, !2}
61: !llvm.ident = !{!3}
62: 
63: !0 = !{i32 1, !"wchar_size", i32 4}
64: !1 = !{i32 7, !"uwtable", i32 1}
65: !2 = !{i32 7, !"frame-pointer", i32 2}
66: !3 = !{!"clang version 13.0.0 (https://github.com/llvm/llvm-project.git d7b669b3a30345cfcdb2fde2af6f48aa4b94845d)"}
67:  """
=== CELL 4 ===
1: Decompiling_IR(IR_code_example)
=== CELL 5 ===
1: def process_bc_file(file_path, output_dir):
2:     try:
3:         with open(file_path, 'rb') as file:
4:             file_content = file.read()
5:             print(f"Successfully read {file_path}")
6:             decompiled_code = Decompiling_IR(file_content)
7:             output_file_name = os.path.basename(file_path).replace('.bc', '.cpp')
8:             output_file_path = os.path.join(output_dir, output_file_name)
9:             with open(output_file_path, 'w') as output_file:
10:                 output_file.write(decompiled_code)
11:             return len(file_content)
12:     except Exception as e:
13:         print(f"Error processing {file_path}: {e}")
14:         return None
=== CELL 6 ===
1: def read_and_process_all_directories(root_dir, output_dir):
2:     processed_files = 0
3:     failed_files = 0
4:     file_names = []
5:     token_lengths_list = []
6:     failed_file_names = []
7:     for subdir, _, files in os.walk(root_dir):
8:         for file in files:
9:             if file.endswith('.bc'):
10:                 file_path = os.path.join(subdir, file)
11:                 token_length = process_bc_file(file_path, output_dir)
12:                 if token_length is not None:
13:                     processed_files += 1
14:                     file_names.append(file)
15:                     token_lengths_list.append(token_length)
16:                 else:
17:                     failed_files += 1
18:                     failed_file_names.append(file)
19:     
20:     return processed_files, failed_files, file_names, failed_file_names,token_lengths_list
=== CELL 7 ===
1: root_directory = "/Users/jianfengzhu/Desktop/Researvh Work/02024AugLLMs_in_IRs/LLMs-in-IR-SEP7/processed_data/Human_x_164_O3"
2: output_directory = "/Users/jianfengzhu/Desktop/Researvh Work/02024AugLLMs_in_IRs/LLMs-in-IR-SEP7/processed_data/ScriptTest/DeepSeekFolder/DeepSeek_Decompile_Result/Run3_DeepSeek_Decompile"
3: 
4: # Ensure the output directory exists
5: os.makedirs(output_directory, exist_ok=True)
6: 
7: processed_files, failed_files, file_names,failed_file_names, token_lengths_list = read_and_process_all_directories(root_directory, output_directory)
=== CELL 8 ===
1: # Generate a table with the statistics
2: df = pd.DataFrame({
3:     'Filename': file_names,
4:     'Token Length': token_lengths_list
5: })
6: 
7: # Print the statistics
8: print(f"Processed Files: {processed_files}")
9: print(f"Failed Files: {failed_files}")
10: # Print the names of failed files
11: if failed_files > 0:
12:     print("Failed file names:")
13:     for file in failed_file_names:
14:         print(file)
15: # Save the DataFrame to a CSV file
16: csv_output_path = "/Users/jianfengzhu/Desktop/LLMs-in-IR/processed_data/Decompiled_Humaneval_x_cpp_164_Result/GPT35_human_x_164_decompiled/processed_files_statistics.csv"
17: df.to_csv(csv_output_path, index=False)
18: print(f"DataFrame saved to {csv_output_path}")
=== FILE Task3_CodeSummary.ipynb ===
=== CELL 0 ===
1: import os
2: import random
3: import openai
4: import pandas as pd
5: import os
6: 
7: # 设置环境变量
8: [REDACTED CREDENTIAL-RELATED LINE]
9: 
10: # 初始化 Groq 客户端
11: import os
12: from together import Together
13: 
14: [REDACTED CREDENTIAL-RELATED LINE]
=== CELL 1 ===
1: ir_code_sample = """; ModuleID = '../../Human_xBenchmarks_164/CPP_0/CPP_0.cpp'
2: source_filename = "../../Human_xBenchmarks_164/CPP_0/CPP_0.cpp"
3: target datalayout = "e-m:e-p270:32:32-p271:32:32-p272:64:64-i64:64-f80:128-n8:16:32:64-S128"
4: target triple = "x86_64-unknown-linux-gnu"
5: 
6: %"class.std::vector" = type { %"struct.std::_Vector_base" }
7: %"struct.std::_Vector_base" = type { %"struct.std::_Vector_base<float, std::allocator<float>>::_Vector_impl" }
8: %"struct.std::_Vector_base<float, std::allocator<float>>::_Vector_impl" = type { %"struct.std::_Vector_base<float, std::allocator<float>>::_Vector_impl_data" }
9: %"struct.std::_Vector_base<float, std::allocator<float>>::_Vector_impl_data" = type { float*, float*, float* }
10: 
11: ; Function Attrs: mustprogress nofree nosync nounwind readonly uwtable willreturn
12: define dso_local zeroext i1 @_Z18has_close_elementsSt6vectorIfSaIfEEf(%"class.std::vector"* nocapture readonly %0, float %1) local_unnamed_addr #0 {
13:   %3 = getelementptr inbounds %"class.std::vector", %"class.std::vector"* %0, i64 0, i32 0, i32 0, i32 0, i32 1
14:   %4 = load float*, float** %3, align 8, !tbaa !3
15:   %5 = getelementptr inbounds %"class.std::vector", %"class.std::vector"* %0, i64 0, i32 0, i32 0, i32 0, i32 0
16:   %6 = load float*, float** %5, align 8, !tbaa !8
17:   %7 = ptrtoint float* %4 to i64
18:   %8 = ptrtoint float* %6 to i64
19:   %9 = sub i64 %7, %8
20:   %10 = ashr exact i64 %9, 2
21:   %11 = icmp eq i64 %9, 0
22:   br i1 %11, label %36, label %12
23: 
24: 12:                                               ; preds = %2
25:   %13 = call i64 @llvm.umax.i64(i64 %10, i64 1)
26:   br label %17
27: 
28: 14:                                               ; preds = %26, %17
29:   %15 = add i64 %19, 1
30:   %16 = icmp eq i64 %21, %13
31:   br i1 %16, label %36, label %17, !llvm.loop !9
32: 
33: 17:                                               ; preds = %12, %14
34:   %18 = phi i64 [ 0, %12 ], [ %21, %14 ]
35:   %19 = phi i64 [ 1, %12 ], [ %15, %14 ]
36:   %20 = phi i1 [ true, %12 ], [ %22, %14 ]
37:   %21 = add nuw i64 %18, 1
38:   %22 = icmp ugt i64 %10, %21
39:   br i1 %22, label %23, label %14
40: 
41: 23:                                               ; preds = %17
42:   %24 = getelementptr inbounds float, float* %6, i64 %18
43:   %25 = load float, float* %24, align 4, !tbaa !11
44:   br label %28
45: 
46: 26:                                               ; preds = %28
47:   %27 = icmp ugt i64 %10, %35
48:   br i1 %27, label %28, label %14, !llvm.loop !13
49: 
50: 28:                                               ; preds = %23, %26
51:   %29 = phi i64 [ %19, %23 ], [ %35, %26 ]
52:   %30 = getelementptr inbounds float, float* %6, i64 %29
53:   %31 = load float, float* %30, align 4, !tbaa !11
54:   %32 = fsub float %25, %31
55:   %33 = tail call float @llvm.fabs.f32(float %32) #3
56:   %34 = fcmp olt float %33, %1
57:   %35 = add i64 %29, 1
58:   br i1 %34, label %36, label %26
59: 
60: 36:                                               ; preds = %14, %28, %2
61:   %37 = phi i1 [ false, %2 ], [ %20, %28 ], [ %22, %14 ]
62:   ret i1 %37
63: }
64: 
65: ; Function Attrs: mustprogress nofree nosync nounwind readnone speculatable willreturn
66: declare float @llvm.fabs.f32(float) #1
67: 
68: ; Function Attrs: nofree nosync nounwind readnone speculatable willreturn
69: declare i64 @llvm.umax.i64(i64, i64) #2
70: 
71: attributes #0 = { mustprogress nofree nosync nounwind readonly uwtable willreturn "frame-pointer"="none" "min-legal-vector-width"="0" "no-trapping-math"="true" "stack-protector-buffer-size"="8" "target-cpu"="x86-64" "target-features"="+cx8,+fxsr,+mmx,+sse,+sse2,+x87" "tune-cpu"="generic" }
72: attributes #1 = { mustprogress nofree nosync nounwind readnone speculatable willreturn }
73: attributes #2 = { nofree nosync nounwind readnone speculatable willreturn }
74: attributes #3 = { nounwind }
75: 
76: !llvm.module.flags = !{!0, !1}
77: !llvm.ident = !{!2}
78: 
79: !0 = !{i32 1, !"wchar_size", i32 4}
80: !1 = !{i32 7, !"uwtable", i32 1}
81: !2 = !{!"clang version 13.0.0 (https://github.com/llvm/llvm-project.git d7b669b3a30345cfcdb2fde2af6f48aa4b94845d)"}
82: !3 = !{!4, !5, i64 8}
83: !4 = !{!"_ZTSNSt12_Vector_baseIfSaIfEE17_Vector_impl_dataE", !5, i64 0, !5, i64 8, !5, i64 16}
84: !5 = !{!"any pointer", !6, i64 0}
85: !6 = !{!"omnipotent char", !7, i64 0}
86: !7 = !{!"Simple C++ TBAA"}
87: !8 = !{!4, !5, i64 0}
88: !9 = distinct !{!9, !10}
89: !10 = !{!"llvm.loop.mustprogress"}
90: !11 = !{!12, !12, i64 0}
91: !12 = !{!"float", !6, i64 0}
92: !13 = distinct !{!13, !10}"""
=== CELL 2 ===
1: 
2: desired_output_format = """
3: There is 1 function in the code, function[1] takes 2 inputs: vector<float> numbers, float threshold. function[1] is checking if any two elements in the vector are closer to each other than the given threshold on numbers, threshold, and outputs a boolean value indicating if such elements exist.
4:     """
=== CELL 3 ===
1: def ir_code_summary(file_content):
2:     prompt = f"""
3:     I will give you an IR code.
4:     Here is the IR code input:
5:         ```
6:         {file_content}
7:         ``` 
8:    I would like you to summarize the code according to the following specifications:
9:    1. **Output Format**:
10:    - There are [n] functions in the code:
11:    - function[I (I in n)] takes [m] inputs: input1, input2, ..., inputm.
12:    - Function[I (I in n)] is [doing semantical function] on input1, input2, ..., inputm, and outputs [output].
13: 
14:    2. **Type and Variable Name Mapping Rules**:
15:    - `% "class.std::vector"*` should be summarized as `vector<float> numbers`.
16:    - Other IR-specific types should be mapped to their equivalent C++ types, following this pattern where possible.
17: 
18:    3. **Strict Adherence to Formatting**:
19:    - The summary should strictly match the format provided below.
20:    - No additional comments, explanations, or deviations from the format should be added.
21:    - Do not use any markdown formatting such as ``` or ```cpp.
22: 
23:     Here is the IR code example to follow:
24:      {ir_code_sample}
25:     The output should exactly match the following format:
26:     {desired_output_format}
27:     **Important Instructions**:
28:     - The summary must not include any additional comments, explanations, or formatting.
29:     - Ensure that variable names and types are directly transcribed as described in the example.
30:     - No markdown formatting (e.g., no ``` or ```cpp) should be used.
31:     **Do not deviate from the specified format under any circumstances.**
32:         """ 
33:     try:
34:         response = client.chat.completions.create(
35:         model="deepseek-ai/DeepSeek-R1-Distill-Llama-70B-free",
36:         messages=[
37:             {"role": "system", "content": "You are an expert in high-performance computation."},
38:             {"role": "user", "content": prompt}
39:         ],
40:     
41:         temperature=0.2
42:             )
43:         analysis = response.choices[0].message.content.strip()
44:         return analysis  
45:     except Exception as e:
46:         print(f"Error during OpenAI API call: {e}")
47:         return None
=== CELL 4 ===
1: ir_code_summary(ir_code_sample)
=== CELL 5 ===
1: def process_bc_file(file_path, output_dir):
2:     
3:     try:
4:         with open(file_path, 'rb') as file:
5:             file_content = file.read()
6:         print(f"Successfully read {file_path}")
7:         
8:         decompiled_code = ir_code_summary(file_content.decode('utf-8', errors='ignore'))
9:         
10:         if decompiled_code:
11:             output_file_name = os.path.basename(file_path).replace('.bc', '.txt')
12:             output_file_path = os.path.join(output_dir, output_file_name)
13:             with open(output_file_path, 'w') as output_file:
14:                 output_file.write(decompiled_code)
15:             return len(file_content)
16:         else:
17:             print(f"Failed to decompile {file_path}")
18:             return None
19:     except Exception as e:
20:         print(f"Error processing {file_path}: {e}")
21:         return None
22: 
23: def read_and_process_all_directories(root_dir, output_dir):
24:     processed_files = 0
25:     failed_files = 0
26:     file_names = []
27:     token_lengths_list = []
28:     failed_file_names = []
29: 
30:     for subdir, dirs, files in os.walk(root_dir):
31:         for dir in dirs:
32:             subfolder_path = os.path.join(subdir, dir)
33:             for file in os.listdir(subfolder_path):
34:                 if file.endswith('.bc'):
35:                     file_path = os.path.join(subfolder_path, file)
36:                     token_length = process_bc_file(file_path, output_dir)
37:                     
38:                     if token_length is not None:
39:                         processed_files += 1
40:                         file_names.append(file)
41:                         token_lengths_list.append(token_length)
42:                     else:
43:                         failed_files += 1
44:                         failed_file_names.append(file)
45:     
46:     return processed_files, failed_files, file_names, token_lengths_list, failed_file_names
=== CELL 6 ===
1: root_directory = "/Users/jianfengzhu/Desktop/Researvh Work/02024AugLLMs_in_IRs/LLMs-in-IR-SEP7/processed_data/Human_x_164_O3"
2: output_directory = "/Users/jianfengzhu/Desktop/Researvh Work/02024AugLLMs_in_IRs/LLMs-in-IR-SEP7/processed_data/ScriptTest/DeepSeekFolder/DeepSeek_CodeSummary_Result/Run3_DeepSeek_CodeSummary"
3: #output_directory = "/Users/jianfengzhu/Desktop/LLMs-in-IR/processed_data/KeyTestExp_Log/ircodesummary_samllsample_result"
4: 
5: # Ensure the output directory exists
6: os.makedirs(output_directory, exist_ok=True)
7: 
8: processed_files, failed_files, file_names, token_lengths_list, failed_file_names = read_and_process_all_directories(root_directory, output_directory)
9: 
10: # Generate a table with the statistics
11: df = pd.DataFrame({
12:     'Filename': file_names,
13:     'Token Length': token_lengths_list
14: })
15: 
16: # Print the statistics
17: print(f"Processed Files: {processed_files}")
18: print(f"Failed Files: {failed_files}")
19: 
20: # Print the names of failed files
21: if failed_files > 0:
22:     print("Failed file names:")
23:     for file in failed_file_names:
24:         print(file)
25: 
=== CELL 7 ===
1: # Save the DataFrame to a CSV file
2: csv_output_path = "/Users/jianfengzhu/Desktop/Researvh Work/02024AugLLMs_in_IRs/LLMs-in-IR-SEP7/processed_data/ScriptTest/DeepSeekFolder/DeepSeek_CodeSummary_Result/Run1_DeepSeek_CodeSummary/completedfile.csv"
3: df.to_csv(csv_output_path, index=False)
=== FILE Task4_Execute_Reasoning.ipynb ===
=== CELL 0 ===
1: import json
2: import os
3: import csv
4: 
5: # Define the paths
6: jsonl_file = "/Users/jianfengzhu/Desktop/LLMs-in-IR-SEP7/Human_xBenchmarks_164/humaneval.jsonl"
7: output_dir = "/Users/jianfengzhu/Desktop/LLMs-in-IR-SEP7/processed_data/Human_x_164_O3"
8: 
9: # Process the input JSONL file
10: with open(jsonl_file, 'r') as file:
11:     for line in file:
12:         # Parse each line as a JSON object
13:         data = json.loads(line)
14:         
15:         # Extract task_id and format it
16:         task_id = data["task_id"].replace("/", "_")
17:         task_file_name = task_id + ".csv"
18:         
19:         # Check if the corresponding file exists in the output directory
20:         task_dir = os.path.join(output_dir, task_id)
21:         if os.path.exists(task_dir):
22:             # Extract assert statements from the test section
23:             test_code = data.get("test", "")
24:             assert_statements = [line.strip() for line in test_code.splitlines() if line.strip().startswith("assert")]
25:             
26:             # Define the CSV file path
27:             output_csv_file = os.path.join(task_dir, task_file_name)
28:             
29:             # Write the assert statements to the CSV file
30:             with open(output_csv_file, 'w', newline='') as csvfile:
31:                 csv_writer = csv.writer(csvfile)
32:                 csv_writer.writerow(["task_id", "assert_statement"])
33:                 for assert_statement in assert_statements:
34:                     csv_writer.writerow([task_id, assert_statement])
35: 
36: print("Extraction and saving of assert statements are complete.")
=== CELL 1 ===
1: import os
2: import random
3: import openai
4: import pandas as pd
5: import os
6: 
7: # 设置环境变量
8: [REDACTED CREDENTIAL-RELATED LINE]
9: 
10: # 初始化 Groq 客户端
11: import os
12: from together import Together
13: 
14: [REDACTED CREDENTIAL-RELATED LINE]
=== CELL 2 ===
1: import os
2: import shutil
3: 
4: # Define the source and destination directories
5: source_dir = "/Users/jianfengzhu/Desktop/LLMs-in-IR-SEP7/Human_xBenchmarks_164"
6: destination_dir = "/Users/jianfengzhu/Desktop/LLMs-in-IR-SEP7/processed_data/Human_x_164_O3"
7: 
8: # Get a list of all subfolders in the source directory
9: subfolders = [f for f in os.listdir(source_dir) if os.path.isdir(os.path.join(source_dir, f))]
10: 
11: # Iterate through each subfolder
12: for subfolder in subfolders:
13:     # Define the full path to the .cpp file in the source directory
14:     cpp_file = os.path.join(source_dir, subfolder, f"{subfolder}.cpp")
15:     
16:     # Define the destination subfolder path
17:     dest_subfolder = os.path.join(destination_dir, subfolder)
18:     
19:     # Check if the .cpp file exists in the source directory
20:     if os.path.exists(cpp_file):
21:         # Copy the .cpp file to the corresponding destination subfolder
22:         shutil.copy(cpp_file, dest_subfolder)
23:         print(f"Copied {cpp_file} to {dest_subfolder}")
24:     else:
25:         print(f"No .cpp file found in {cpp_file}")
=== CELL 3 ===
1: final_result = """### final result
2:                 - **assertion result**: **pass** """
3: def SC_evaluate_assertion_with_api(SC_code, assertion):
4:     try:
5:         prompt = (
6:             "You are an expert in C/C++ programming and code analysis. Your task is to analyze whether the provided assertion passes or fails based on the given C/C++ code for a function.\n\n"
7:             "### C/C++ Code\n"
8:             "```\n"
9:             f"{SC_code}\n"
10:             "```\n\n"
11:             "### Assertion Statement\n"
12:             f"```\n{assertion}\n```\n\n"
13:             "Please write down your thinking process, and list the pass/fail result of each assertion at the end."
14:             "NOTE: Make sure the format the pass/fail result of each assertion at the end follow the example:"
15:             f"\n{final_result}"
16:         )
17:         # Call the OpenAI API with the prompt
18:         response =client.chat.completions.create(
19:             model="deepseek-ai/DeepSeek-R1-Distill-Llama-70B-free",
20:             messages=[
21:                 {"role": "user", "content": prompt},
22:             ],
23:             temperature=0.2,
24:         )
25: 
26:         # Extract the result
27:         result = response.choices[0].message.content.strip().lower()
28:         return result
29:     
30:     except Exception as e:
31:         if 'context_length_exceeded' in str(e):
32:             return "fail to read"
33:         else:
34:             return "error"
=== CELL 4 ===
1: def extract_final_result(full_text):
2:     """
3:     Extracts the final result ("pass" or "fail") and comments from the analysis.
4:     """
5:     try:
6:         # Extract the final result (pass or fail) from the text
7:         final_result = "unknown"
8:         comment = full_text
9:         
10:         # Extract the final result line
11:         if "**assertion result**: **pass**" in full_text.lower():
12:             final_result = "pass"
13:         elif "**assertion result**: **fail**" in full_text.lower():
14:             final_result = "fail"
15: 
16:         return final_result, comment
17:     except Exception as e:
18:         return "error", str(e)
=== CELL 5 ===
1: def process_folder(folder, relative_folder):
2:     SC_file = None
3:     csv_file = None
4:     
5:     # Identify the .bc and .csv files
6:     for file in os.listdir(folder):
7:         if file.endswith('.cpp'):
8:             SC_file = os.path.join(folder, file)
9:         elif file.endswith('.csv'):
10:             csv_file = os.path.join(folder, file)
11:     
12:     if not SC_file or not csv_file:
13:         print(f"Missing files in {folder}")
14:         return
15:     
16:     # Read the source code from the .bc file (assuming .cpp files are in LLVM bitcode text format)
17:     with open(SC_file, 'r') as file:
18:         SC_code = file.read()
19:     
20:     # Read the CSV file
21:     df = pd.read_csv(csv_file)
22:     
23:     # Prepare a list to store results
24:     results = []
25:     
26:     # Analyze each assertion statement
27:     for index, row in df.iterrows():
28:         assertion = row['assert_statement']
29:         
30:         # Evaluate the assertion using the OpenAI API
31:         full_analysis = SC_evaluate_assertion_with_api(SC_code, assertion)
32:         
33:         # Extract the final result and comment
34:         final_result, comment = extract_final_result(full_analysis)
35:         
36:         # Append to results list
37:         results.append([assertion, final_result, comment])
38:     
39:     # Create a DataFrame from the results
40:     result_df = pd.DataFrame(results, columns=['assert_statement', 'final_result', 'comment'])
41:     
42:     # Prepare the output folder
43:     output_folder = os.path.join(output_base_dir, relative_folder)
44:     os.makedirs(output_folder, exist_ok=True)
45:     
46:     # Define the output CSV file path
47:     output_file = os.path.join(output_folder, 'assertion_results.csv')
48:     
49:     # Save the results to a CSV file
50:     result_df.to_csv(output_file, index=False)
51: 
52:     print(f"Results saved to {output_file}")
=== CELL 6 ===
1: 
2: # Example of how to call the function
3: # Define the base directories
4: input_base_dir = '/Users/jianfengzhu/Desktop/Researvh Work/02024AugLLMs_in_IRs/LLMs-in-IR-SEP7/processed_data/Human_x_164_O3'
5: output_base_dir = '/Users/jianfengzhu/Desktop/Researvh Work/02024AugLLMs_in_IRs/LLMs-in-IR-SEP7/processed_data/ScriptTest/DeepSeekFolder/DeepSeek_Execute_Result/Run3_DeepSeek_Execute'
6: 
7: # Ensure the output base directory exists
8: os.makedirs(output_base_dir, exist_ok=True)
9: # Assume each folder under the input_base_dir needs to be processed
10: for folder_name in os.listdir(input_base_dir):
11:     folder_path = os.path.join(input_base_dir, folder_name)
12:     if os.path.isdir(folder_path):
13:         process_folder(folder_path, folder_name)
=== CELL 7 ===
1: def extract_final_result(full_text):
2:     """
3:     Extracts the final result ("pass" or "fail") and comments from the analysis.
4:     """
5:     try:
6:         # Extract the final result (pass or fail) from the text
7:         final_result = "unknown"
8:         comment = full_text
9:         
10:         # Extract the final result line
11:         if "**assertion result**: **pass**" in full_text.lower():
12:             final_result = "pass"
13:         elif "**assertion result**: **fail**" in full_text.lower():
14:             final_result = "fail"
15: 
16:         return final_result, comment
17:     except Exception as e:
18:         return "error", str(e)
=== CELL 8 ===
1: def process_folder(folder, relative_folder):
2:     SC_file = None
3:     csv_file = None
4:     
5:     # Identify the .bc and .csv files
6:     for file in os.listdir(folder):
7:         if file.endswith('.cpp'):
8:             SC_file = os.path.join(folder, file)
9:         elif file.endswith('.csv'):
10:             csv_file = os.path.join(folder, file)
11:     
12:     if not SC_file or not csv_file:
13:         print(f"Missing files in {folder}")
14:         return
15:     
16:     # Read the source code from the .bc file (assuming .cpp files are in LLVM bitcode text format)
17:     with open(SC_file, 'r') as file:
18:         SC_code = file.read()
19:     
20:     # Read the CSV file
21:     df = pd.read_csv(csv_file)
22:     
23:     # Prepare a list to store results
24:     results = []
25:     
26:     # Analyze each assertion statement
27:     for index, row in df.iterrows():
28:         assertion = row['assert_statement']
29:         
30:         # Evaluate the assertion using the OpenAI API
31:         full_analysis = SC_evaluate_assertion_with_Tapi(SC_code, assertion)
32:         
33:         # Extract the final result and comment
34:         final_result, comment = extract_final_result(full_analysis)
35:         
36:         # Append to results list
37:         results.append([assertion, final_result, comment])
38:     
39:     # Create a DataFrame from the results
40:     result_df = pd.DataFrame(results, columns=['assert_statement', 'final_result', 'comment'])
41:     
42:     # Prepare the output folder
43:     output_folder = os.path.join(output_base_dir, relative_folder)
44:     os.makedirs(output_folder, exist_ok=True)
45:     
46:     # Define the output CSV file path
47:     output_file = os.path.join(output_folder, 'assertion_results.csv')
48:     
49:     # Save the results to a CSV file
50:     result_df.to_csv(output_file, index=False)
51: 
52:     print(f"Results saved to {output_file}")