Source

Opifex / src / Transformation / CWCPS / CWCPS_RemoveDeadCode.ml

Full commit
(*
 * Opifex
 *
 * Copyrights(C) 2012 by Pawel Wieczorek <wieczyk at gmail>
 *)

open CWCPS_AST
open CWCPS_Transformation
open Batteries

(*************************************************************************************************
 * Unused definitions
 ************************************************************************************************)

module UnusedDefinitions = struct

    let substitute_vexpr result i = Transformation.Substitute [ (result, i) ]

    let substitute_int result i   = substitute_vexpr result (VEXPR_Integer i)

    let is_var_used usage_count var = usage_count var > 0

    let try_remove_definition usage_count var in_expr =
        if is_var_used usage_count var
        then Transformation.NoChange 
        else Transformation.Replace in_expr

    let transformation usage_count = function

        (* optimalize unused fixs *)

        | EXPR_Fix (reclabel, [], in_expr) ->
            Transformation.Replace in_expr

        | EXPR_Fix (reclabel, definitions, in_expr) ->
            let definitions' = List.filter (is_var_used usage_count  -| get_name_from_fixdef) definitions in
            begin match definitions' with
            | [] ->
                Transformation.Replace in_expr

            | _ ->
                if List.length definitions = List.length definitions'
                then Transformation.NoChange
                else Transformation.Replace (EXPR_Fix (reclabel, definitions', in_expr))
            end

        (* unused result of arithmetic operations *)

        | EXPR_ArithmeticBinaryPrimOp (_, _, _, _, result, in_expr) 
        | EXPR_ArithmeticUnaryPrimOp (_, _, _, result, in_expr) ->
            try_remove_definition usage_count result in_expr 

            
        | _ ->
            Transformation.NoChange
end

(*************************************************************************************************
 * 
 ************************************************************************************************)

let bottomup_transformations = 
    [ UnusedDefinitions.transformation
    ]

let bottomup =
    Transformation.bottomups_with_analysis
        CWCPS_VariableUsageAnalysis.UsageCountingAnalysis.analyze
        bottomup_transformations