PLC-lang / rusty

Structured Text Parser and LLVM Frontend
GNU Lesser General Public License v3.0
183 stars 48 forks source link

LLVM Code Coverage Instrumentation #1088

Open corbanvilla opened 3 months ago

corbanvilla commented 3 months ago

Overview

Related Issue

Description

This PR includes all of the necessary code to introduce code coverage instrumentation into Rusty. It's a large PR with still lots of work to be done, but provides a proof of concept and reference point for some necessary discussions.

Code Coverage Instrumentation Process

  1. CodeGen::new(...): Create a CoverageInstrumentationBuilder
  2. CodeGen::generate_llvm_index(...): add increment function to llvm_index.
  3. CodeGen::generate(...):
    • Generate the coverage mapping header in the module.
    • Generate function records in the module, along with Profile-guided optimization (PGO) variables for each function.
      • Even though we don't use PGO in the compilation, these variables are used by the coverage instrumentation pass.
      • This process includes running a DFS algorithm through each function and creating coverage counters and mapping regions throughout control flow.
  4. CodeGen::generate(...) -> PouGenerator::generate_implementation(...):
    • Add a counter increment right before the function body begins to execute.
    • Add counter increments when entering control flow regions.
  5. CodeGen::generate(...): call the LLVM instrumentation coverage pass (instrprof) to run on the IR.
    • From my understanding, this pass needs to run even when the target output is IR (the pass can't be run later by clang, for example). This is because it replaces the increment calls with other instructions, and the increment function calls are not actually callable.

Overview of Changes

Discussion Points

TODOs

Examples

Screenshot 2024-01-31 at 10 51 16 PM Screenshot 2024-01-31 at 10 50 51 PM

riederm commented 3 months ago

hey @corbanvilla,

first of all, thx for your contribution. This PR is pretty big, and also the topics are quite new to rusty, so I guess we should discuss further on how we best integrate these things. I'm afraid if we keep such a big PR pending for too long it will diverge more and more.

I'll see if I can talk to the other maintainers soon but I really like that you already suggested some discussion points. ghaith already contributed into inkwell in the past, it should be failry streight forward to decide if this can be suggested to the inkwell project right away. I'll poke ghaith today when I see him.

thx again! we'll keep in touch

ghaith commented 3 months ago

Hello @corbanvilla,

Thank you for the PR. I didn't get the chance to look into it in details, but from your comments and first glance I just have a few small points.