#!/bin/bash

# file doc/genscripts/004-gimplessa-mallfree.sh this script is running
# in doc/ directory and extracts the gimple and SSA forms of
# examples/mallfree.c

printf "@@@BISMONDOC starting %s %s cwd %s:\n" "$0" "$@" $(pwd) > /dev/stderr

source genscripts/straight-gcc-config.bash
cd generated/

echo running genscripts/004-gimplessa-mallfree.sh in $(pwd) 1>&2
$GCC -O3 -S  -fdump-tree-gimple  -fdump-tree-ssa -fdump-tree-optimized -fverbose-asm ../examples/mallfree.c 1>&2
(ls -ls $PWD/mallfree*) 1>&2

if [ ! -f mallfree.c.0*t.gimple ]; then
    echo missing single 'mallfree.c.0*t.gimple' file > /dev/stderr
    exit 1
fi
echo "//" mallfree.c.0*t.gimple "generated by ..." >> mallfree.c.0*t.gimple
echo "//... $XGCC -O3 -S -fverbose-asm \\" >> mallfree.c.0*t.gimple
echo "//...  -fdump-tree-gimple  -fdump-tree-ssa -fdump-tree-optimized mallfree.c" >> mallfree.c.0*t.gimple

if [ ! -f mallfree.c.[0-9]*t.gimple ]; then
    echo missing single 'mallfree.c.[0-9]*t.gimple' file > /dev/stderr
    exit 1
fi
ln -svf mallfree.c.0*t.gimple $PWD/mallfree-gimple.c 1>&2

if [ ! -f mallfree.c.[0-9]*t.ssa ]; then
    echo missing single 'mallfree.c.[0-9]*t.ssa' file > /dev/stderr
    exit 1
fi
ln -svf mallfree.c.[0-9]*t.ssa $PWD/mallfree-ssa.c 1>&2
sed -i mallfree-ssa.c -e '1,2s/decl_uid/\n;;;  decl_uid/'

ln -svf mallfree.c.[0-9]*t.optimized $PWD/mallfree-optimized.c 1>&2
sed -i mallfree-optimized.c -e '1,2s/decl_uid/\n;;;  decl_uid/'

nbskip=$(fgrep -n .text mallfree.s | cut -d: -f1)
printf "## %d lines removed\n" $nbskip > mallfree-tail.s
tail -n +$nbskip mallfree.s | sed s:../examples/::g >> mallfree-tail.s

(pwd; ls -ls mallfree*)  1>&2

printf "%% 004-gimplessa-mallfree.sh done\n"
