Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use comments in LLVM IR in my pass?

Tags:

llvm

Is it possible to use the comments in IR in my pass? Basically I want to use the IR annotated with basic block frequency, which is written in comments, as shown below, and I need the frequency value in my pass. I know this is naive method, but it will suffice.

define internal void @MDFilter() #0 {  
entry:  
    ;;; Basic block executed 2 times.  <-- I NEED THIS COMMENT AS A STRING IN MY PASS
  %mdContext = alloca %struct.MD5_CTX, align 8  
  %bytes = alloca i32, align 4  
  %data = alloca [16 x i8], align 16  
  call void @MD5Init(%struct.MD5_CTX* %mdContext)  
  br label %while.cond  
    ;;; Out-edge counts: [2.000000e+00 -> while.cond]  

Any other method to obtain this info is also welcome.

like image 516
shrm Avatar asked Sep 13 '25 05:09

shrm


1 Answers

No, there is no way to use the comments' contents this way, not without significantly changing the IR parser. However, there's no need to re-invent the wheel; there's a mechanism in LLVM which is intended precisely for these sorts of things - transferring information from the front-end into an LLVM pass - and that is metadata.

So whatever or whoever is adding this information to the IR should add it with metadata instead - see these sources for more information on how to do that:

  • http://llvm.org/docs/LangRef.html#metadata
  • http://llvm.org/docs/LangRef.html#named-metadata
  • Adding Metadata to Instructions in LLVM IR
  • How to attach metadata to LLVM IR using the C++ API?
  • How to add a Metadata String to an LLVM module with the C++ API?

If you have no control over the generation of data, then you should add some pre-processing step in which you convert the comments to metadata.

In the end the IR should look something like:

define internal void @MDFilter() #0 {  
entry:  
  %mdContext = alloca %struct.MD5_CTX, align 8, !freq !1
  %bytes = alloca i32, align 4  
  %data = alloca [16 x i8], align 16  
  call void @MD5Init(%struct.MD5_CTX* %mdContext)  
  br label %while.cond, !outedge !2

...

!1 = metadata !{i32 2}
!2 = metadata !{float 2.0}

And your pass needs to look for these !freq and !outedge nodes.

like image 102
Oak Avatar answered Sep 16 '25 07:09

Oak