#!/bin/sh

. ./conf.py

{ test -f linux/.config && test -f linux/vmlinux.original; } || {
	echo "linux/.config or linux/vmlinux.original does not exist"
	exit 1
}
grep -q ^CONFIG_OPTIMIZE_INLINING=y linux/.config && {
	echo -n "\
Warning: CONFIG_OPTIMIZE_INLINING is selected.
gcc can spuriously deinline inlines, generating many duplicate
functions in vmlinux and making it hard to measure inline bloat. See
	https://gcc.gnu.org/bugzilla/show_bug.cgi?id=66122
"
}
grep -q ^CONFIG_CC_OPTIMIZE_FOR_SIZE=y linux/.config || {
	echo -n "\
Warning: CONFIG_CC_OPTIMIZE_FOR_SIZE is not selected.
Alignment padding will make code size measurement less stable.
"
}


echo "Finding, sorting and filtering inlines for testing"
test -f linux/conf.py && exit 1
(
cd linux || exit 1
cp ../conf.py .
../01find_inlines >inlines.log
../02sort_inlines inlines.log
rm -f conf.py
) 2>&1 | tee -a inlines_err.log
test -f linux/inlines.log.filtered || {
	echo "linux/inlines.log.filtered does not exist"
	exit 1
}
mv linux/inlines.log* .


test -e "WORK" && { echo "WORK/ exists, please check it"; exit 1; }
echo "Making WORK/ files"
mkdir -p "WORK"
oldfl=""
seq=0
outname=`printf "w.%d" "$seq"`
exec <"inlines.log.filtered"
while IFS=: read -r file line func line_cnt; do
	if test x"$file" != x"$oldfl"; then
		seq=$((seq+1))
		outname=`printf "w.%d" "$seq"`
	fi
	echo "$file:$line:$func:$line_cnt" >>"WORK/$outname"
	oldfl="$file"
done
seq=0
(cd WORK && for f in `ls -1S`; do
	test -f "$f" || continue
	seq=$((seq+1))
	outname=`printf "inlines.log.filtered.%05d" "$seq"`
	mv "$f" "$outname"
done)


echo "Making $dir_count copies of linux/"
# These are huge, not used by us and easily rebuilt.
# Save time not copying them N times:
rm -f linux/.tmp_vmlinux* linux/vmlinux.o linux/vmlinux
for n in `seq 1 $dir_count`; do
	cp -a linux linux.$n || exit 1
	echo "Done: linux.$n"
done
echo "Remaining free space:"
df -h .


echo "Spawning inline size measuring jobs in linux.*"
for n in `seq 1 $dir_count`; do
	(
	cd linux.$n || exit 1
	setsid nice -n17 ../03rebuild_inlines ../WORK >>inlines.log.measured 2>>inlines_err.log &
	)
	echo -n .
done
echo "Done"
