Skip to content

Instantly share code, notes, and snippets.

@roz0n
Created April 10, 2024 05:16
Show Gist options
  • Save roz0n/1cc51dedf62eda6f9218b303ed589e37 to your computer and use it in GitHub Desktop.
Save roz0n/1cc51dedf62eda6f9218b303ed589e37 to your computer and use it in GitHub Desktop.
Automates the process of transforming a Swift file through the various stages of compilation: from Swift code to SIL, from SIL to LLVM IR, and finally to assembly.
#!/bin/bash
# Check if an argument (Swift file name) was provided
if [ "$#" -ne 1 ]; then
echo "Usage: $0 <Swift File>"
exit 1
fi
SWIFT_FILE=$1
BASE_NAME=${SWIFT_FILE%.*}
# Get script name without the path and extension for folder naming
SCRIPT_NAME=$(basename "$0" .sh)
# Create a timestamp in the format of YearMonthDay-HourMinuteSecond (e.g., 20230415-123045)
TIMESTAMP=$(date "+%Y%m%d-%H%M%S")
# Create a directory with the script name and timestamp
OUTPUT_DIR="${SCRIPT_NAME}_${TIMESTAMP}"
mkdir -p "$OUTPUT_DIR"
# Ensure the file exists
if [ ! -f "$SWIFT_FILE" ]; then
echo "File not found: $SWIFT_FILE"
exit 1
fi
echo "Compiling $SWIFT_FILE into directory $OUTPUT_DIR..."
# Step 1: Compile Swift to SIL
echo "Emitting SIL..."
swiftc -emit-sil "$SWIFT_FILE" > "${OUTPUT_DIR}/${BASE_NAME}.sil"
echo "SIL output saved to ${OUTPUT_DIR}/${BASE_NAME}.sil"
# Step 2: Compile Swift to LLVM IR
echo "Emitting LLVM IR..."
swiftc -emit-ir "$SWIFT_FILE" > "${OUTPUT_DIR}/${BASE_NAME}.ll"
echo "LLVM IR output saved to ${OUTPUT_DIR}/${BASE_NAME}.ll"
# Step 3: Compile Swift to Assembly
echo "Emitting Assembly..."
swiftc -S "$SWIFT_FILE" > "${OUTPUT_DIR}/${BASE_NAME}.s"
echo "Assembly output saved to ${OUTPUT_DIR}/${BASE_NAME}.s"
# Final Compilation (optional, uncomment if desired)
# echo "Compiling to executable..."
# swiftc "$SWIFT_FILE" -o "${OUTPUT_DIR}/${BASE_NAME}"
# echo "Executable created: ${OUTPUT_DIR}/${BASE_NAME}"
echo "Compilation steps completed."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment