Compare commits

...

4 Commits

Author SHA1 Message Date
David Mak 1d0356e3c4 meta: Update run_demo.sh
- Allow more than one argument to nac3standalone executable
- Abort linking process if standalone executable exits with error
2023-09-06 20:25:37 +08:00
David Mak 95222331b6 standalone: Expose flags in command-line 2023-09-06 20:25:35 +08:00
David Mak 5165e61507 core: Add opt_level and emit_llvm to CodeGen options 2023-09-06 20:25:23 +08:00
David Mak a335a317c5 standalone: Implement command-line parser using clap
In preparation for adding more command-line options.
2023-09-06 20:25:22 +08:00
6 changed files with 182 additions and 19 deletions

113
Cargo.lock generated
View File

@ -34,6 +34,54 @@ dependencies = [
"memchr", "memchr",
] ]
[[package]]
name = "anstream"
version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b1f58811cfac344940f1a400b6e6231ce35171f614f26439e80f8c1465c5cc0c"
dependencies = [
"anstyle",
"anstyle-parse",
"anstyle-query",
"anstyle-wincon",
"colorchoice",
"utf8parse",
]
[[package]]
name = "anstyle"
version = "1.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "15c4c2c83f81532e5845a733998b6971faca23490340a418e9b72a3ec9de12ea"
[[package]]
name = "anstyle-parse"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "938874ff5980b03a87c5524b3ae5b59cf99b1d6bc836848df7bc5ada9643c333"
dependencies = [
"utf8parse",
]
[[package]]
name = "anstyle-query"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5ca11d4be1bab0c8bc8734a9aa7bf4ee8316d462a08c6ac5052f888fef5b494b"
dependencies = [
"windows-sys 0.48.0",
]
[[package]]
name = "anstyle-wincon"
version = "2.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "58f54d10c6dfa51283a066ceab3ec1ab78d13fae00aa49243a45e4571fb79dfd"
dependencies = [
"anstyle",
"windows-sys 0.48.0",
]
[[package]] [[package]]
name = "ascii-canvas" name = "ascii-canvas"
version = "3.0.0" version = "3.0.0"
@ -94,6 +142,52 @@ version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd"
[[package]]
name = "clap"
version = "4.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6a13b88d2c62ff462f88e4a121f17a82c1af05693a2f192b5c38d14de73c19f6"
dependencies = [
"clap_builder",
"clap_derive",
]
[[package]]
name = "clap_builder"
version = "4.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2bb9faaa7c2ef94b2743a21f5a29e6f0010dff4caa69ac8e9d6cf8b6fa74da08"
dependencies = [
"anstream",
"anstyle",
"clap_lex",
"strsim",
]
[[package]]
name = "clap_derive"
version = "4.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0862016ff20d69b84ef8247369fabf5c008a7417002411897d40ee1f4532b873"
dependencies = [
"heck",
"proc-macro2",
"quote",
"syn 2.0.29",
]
[[package]]
name = "clap_lex"
version = "0.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cd7cc57abe963c6d3b9d8be5b06ba7c8957a930305ca90304f24ef040aa6f961"
[[package]]
name = "colorchoice"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "acbf1af155f9b9ef647e42cdc158db4b64a1b61f743629225fde6f3e0be2a7c7"
[[package]] [[package]]
name = "console" name = "console"
version = "0.15.7" version = "0.15.7"
@ -313,6 +407,12 @@ version = "0.12.3"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888" checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888"
[[package]]
name = "heck"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "95505c38b4572b2d910cecb0281560f54b440a19336cbbcb27bf6ce6adc6f5a8"
[[package]] [[package]]
name = "hermit-abi" name = "hermit-abi"
version = "0.3.2" version = "0.3.2"
@ -618,6 +718,7 @@ dependencies = [
name = "nac3standalone" name = "nac3standalone"
version = "0.1.0" version = "0.1.0"
dependencies = [ dependencies = [
"clap",
"inkwell", "inkwell",
"nac3core", "nac3core",
"nac3parser", "nac3parser",
@ -1079,6 +1180,12 @@ dependencies = [
"precomputed-hash", "precomputed-hash",
] ]
[[package]]
name = "strsim"
version = "0.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "73473c0e59e6d5812c5dfe2a064a6444949f089e20eec9a2e5506596494e4623"
[[package]] [[package]]
name = "syn" name = "syn"
version = "1.0.109" version = "1.0.109"
@ -1288,6 +1395,12 @@ version = "0.1.11"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e1766d682d402817b5ac4490b3c3002d91dfa0d22812f341609f97b08757359c" checksum = "e1766d682d402817b5ac4490b3c3002d91dfa0d22812f341609f97b08757359c"
[[package]]
name = "utf8parse"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "711b9620af191e0cdc7468a8d14e709c3dcdb115b36f838e601583af800a370a"
[[package]] [[package]]
name = "version_check" name = "version_check"
version = "0.9.4" version = "0.9.4"

View File

@ -601,6 +601,8 @@ pub fn gen_func_instance<'ctx, 'a>(
store, store,
unifier_index: instance.unifier_id, unifier_index: instance.unifier_id,
id, id,
opt_level: ctx.opt_level,
emit_llvm: ctx.emit_llvm,
}); });
Ok(symbol) Ok(symbol)
} else { } else {

View File

@ -89,6 +89,10 @@ pub struct CodeGenContext<'ctx, 'a> {
Option<(Vec<Option<BasicValueEnum<'ctx>>>, BasicBlock<'ctx>, PhiValue<'ctx>)>, Option<(Vec<Option<BasicValueEnum<'ctx>>>, BasicBlock<'ctx>, PhiValue<'ctx>)>,
pub need_sret: bool, pub need_sret: bool,
pub current_loc: Location, pub current_loc: Location,
/// The optimization level to apply on the generated LLVM IR.
pub opt_level: OptimizationLevel,
/// Whether to output the LLVM IR after generation is complete.
pub emit_llvm: bool,
} }
impl<'ctx, 'a> CodeGenContext<'ctx, 'a> { impl<'ctx, 'a> CodeGenContext<'ctx, 'a> {
@ -225,24 +229,32 @@ impl WorkerRegistry {
context.i32_type().const_int(4, false), context.i32_type().const_int(4, false),
); );
let passes = PassManager::create(&module);
// HACK: This critical section is a work-around for issue
// https://git.m-labs.hk/M-Labs/nac3/issues/275
{
let _data = PASSES_INIT_LOCK.lock();
let pass_builder = PassManagerBuilder::create();
pass_builder.set_optimization_level(OptimizationLevel::Default);
pass_builder.populate_function_pass_manager(&passes);
}
let mut errors = HashSet::new(); let mut errors = HashSet::new();
while let Some(task) = self.receiver.recv().unwrap() { while let Some(task) = self.receiver.recv().unwrap() {
let passes = PassManager::create(&module);
// HACK: This critical section is a work-around for issue
// https://git.m-labs.hk/M-Labs/nac3/issues/275
{
let _data = PASSES_INIT_LOCK.lock();
let pass_builder = PassManagerBuilder::create();
pass_builder.set_optimization_level(task.opt_level);
pass_builder.populate_function_pass_manager(&passes);
}
let emit_llvm = task.emit_llvm;
match gen_func(&context, generator, self, builder, module, task) { match gen_func(&context, generator, self, builder, module, task) {
Ok(result) => { Ok(result) => {
builder = result.0; builder = result.0;
passes.run_on(&result.2); passes.run_on(&result.2);
module = result.1; module = result.1;
if emit_llvm {
println!("LLVM IR for {}", module.get_name().to_str().unwrap());
println!("{}", module.to_string());
println!();
}
} }
Err((old_builder, e)) => { Err((old_builder, e)) => {
builder = old_builder; builder = old_builder;
@ -264,6 +276,7 @@ impl WorkerRegistry {
println!("{}", err.to_string()); println!("{}", err.to_string());
panic!() panic!()
} }
f.run(&module); f.run(&module);
let mut lock = self.task_count.lock(); let mut lock = self.task_count.lock();
*lock += 1; *lock += 1;
@ -281,6 +294,10 @@ pub struct CodeGenTask {
pub unifier_index: usize, pub unifier_index: usize,
pub resolver: Arc<dyn SymbolResolver + Send + Sync>, pub resolver: Arc<dyn SymbolResolver + Send + Sync>,
pub id: usize, pub id: usize,
/// The optimization level to apply on the generated LLVM IR.
pub opt_level: OptimizationLevel,
/// Whether to output the LLVM IR after generation is complete.
pub emit_llvm: bool,
} }
fn get_llvm_type<'ctx>( fn get_llvm_type<'ctx>(
@ -624,7 +641,7 @@ pub fn gen_func_impl<'ctx, G: CodeGenerator, F: FnOnce(&mut G, &mut CodeGenConte
), ),
/* directory */ "", /* directory */ "",
/* producer */ "NAC3", /* producer */ "NAC3",
/* is_optimized */ true, /* is_optimized */ task.opt_level != OptimizationLevel::None,
/* compiler command line flags */ "", /* compiler command line flags */ "",
/* runtime_ver */ 0, /* runtime_ver */ 0,
/* split_name */ "", /* split_name */ "",
@ -659,7 +676,7 @@ pub fn gen_func_impl<'ctx, G: CodeGenerator, F: FnOnce(&mut G, &mut CodeGenConte
/* is_definition */ true, /* is_definition */ true,
/* scope_line */ row as u32, /* scope_line */ row as u32,
/* flags */ inkwell::debug_info::DIFlags::PUBLIC, /* flags */ inkwell::debug_info::DIFlags::PUBLIC,
/* is_optimized */ true, /* is_optimized */ task.opt_level != OptimizationLevel::None,
); );
fn_val.set_subprogram(func_scope); fn_val.set_subprogram(func_scope);
@ -686,6 +703,8 @@ pub fn gen_func_impl<'ctx, G: CodeGenerator, F: FnOnce(&mut G, &mut CodeGenConte
need_sret: has_sret, need_sret: has_sret,
current_loc: Default::default(), current_loc: Default::default(),
debug_info: (dibuilder, compile_unit, func_scope.as_debug_info_scope()), debug_info: (dibuilder, compile_unit, func_scope.as_debug_info_scope()),
opt_level: task.opt_level,
emit_llvm: task.emit_llvm,
}; };
let loc = code_gen_context.debug_info.0.create_debug_location( let loc = code_gen_context.debug_info.0.create_debug_location(

View File

@ -9,6 +9,10 @@ parking_lot = "0.12"
nac3parser = { path = "../nac3parser" } nac3parser = { path = "../nac3parser" }
nac3core = { path = "../nac3core" } nac3core = { path = "../nac3core" }
[dependencies.clap]
version = "4.4"
features = ["derive"]
[dependencies.inkwell] [dependencies.inkwell]
version = "0.2" version = "0.2"
default-features = false default-features = false

View File

@ -15,6 +15,6 @@ else
fi fi
rm -f *.o rm -f *.o
$nac3standalone $1 $nac3standalone "$@" || exit $?
rustc -o demo demo.rs -Crelocation-model=static -Clink-arg=./module.o rustc -o demo demo.rs -Crelocation-model=static -Clink-arg=./module.o || exit $?
./demo ./demo

View File

@ -1,3 +1,4 @@
use clap::Parser;
use inkwell::{ use inkwell::{
memory_buffer::MemoryBuffer, memory_buffer::MemoryBuffer,
passes::{PassManager, PassManagerBuilder}, passes::{PassManager, PassManagerBuilder},
@ -5,7 +6,8 @@ use inkwell::{
OptimizationLevel, OptimizationLevel,
}; };
use parking_lot::{Mutex, RwLock}; use parking_lot::{Mutex, RwLock};
use std::{borrow::Borrow, collections::HashMap, env, fs, path::Path, sync::Arc}; use std::{borrow::Borrow, collections::HashMap, fs, path::Path, sync::Arc};
use std::mem::transmute;
use nac3core::{ use nac3core::{
codegen::{ codegen::{
@ -30,6 +32,26 @@ use nac3parser::{
mod basic_symbol_resolver; mod basic_symbol_resolver;
use basic_symbol_resolver::*; use basic_symbol_resolver::*;
/// Command-line argument parser definition.
#[derive(Parser)]
#[command(author, version, about, long_about = None)]
struct CommandLineArgs {
/// The name of the input file.
file_name: String,
/// The number of threads allocated to processing the source file.
#[arg(default_value_t = 1)]
threads: u32,
/// The level to optimize the LLVM IR.
#[arg(short = 'O', default_value_t = 2, value_parser = clap::value_parser!(u32).range(0..=3))]
opt_level: u32,
/// Whether to emit LLVM IR at the end of every module.
#[arg(long, default_value_t = false)]
emit_llvm: bool,
}
fn handle_typevar_definition( fn handle_typevar_definition(
var: &Expr, var: &Expr,
resolver: &(dyn SymbolResolver + Send + Sync), resolver: &(dyn SymbolResolver + Send + Sync),
@ -155,8 +177,9 @@ fn handle_assignment_pattern(
} }
fn main() { fn main() {
let file_name = env::args().nth(1).unwrap(); let cli = CommandLineArgs::parse();
let threads: u32 = env::args().nth(2).map(|s| str::parse(&s).unwrap()).unwrap_or(1); let CommandLineArgs { file_name, threads, opt_level, emit_llvm } = cli;
let opt_level: OptimizationLevel = unsafe { transmute(opt_level) };
Target::initialize_all(&InitializationConfig::default()); Target::initialize_all(&InitializationConfig::default());
@ -252,6 +275,8 @@ fn main() {
unifier_index: instance.unifier_id, unifier_index: instance.unifier_id,
calls: instance.calls, calls: instance.calls,
id: 0, id: 0,
opt_level,
emit_llvm,
}; };
let membuffers: Arc<Mutex<Vec<Vec<u8>>>> = Default::default(); let membuffers: Arc<Mutex<Vec<Vec<u8>>>> = Default::default();
@ -305,7 +330,7 @@ fn main() {
&triple, &triple,
"", "",
"", "",
OptimizationLevel::Default, opt_level,
RelocMode::Default, RelocMode::Default,
CodeModel::Default, CodeModel::Default,
) )