Compare commits

..

132 Commits

Author SHA1 Message Date
David
4bfbd5ded5
Merge pull request #249 from birth-software/introduce-polymorphism
Introduce plain type polymorphism
2024-06-18 18:52:49 -05:00
David Gonzalez Martin
3d9d26ea82 Introduce plain type polymorphism 2024-06-18 18:45:19 -05:00
David
fee5ed17e5
Merge pull request #248 from birth-software/better-di
Produce better pointer and slice debug info names
2024-06-17 14:34:35 -05:00
David Gonzalez Martin
53894589ff Produce better pointer and slice debug info names 2024-06-17 14:31:25 -05:00
David
11f70a1d9e
Merge pull request #247 from birth-software/hello-world-string
Hello world string
2024-06-17 13:39:46 -05:00
David Gonzalez Martin
610faec907 Hello world string 2024-06-17 13:35:32 -05:00
David
200cc7b76e
Merge pull request #246 from birth-software/hello-world-array
Hello world array
2024-06-16 19:23:54 -05:00
David Gonzalez Martin
06f9fe3597 Hello world array 2024-06-16 19:21:12 -05:00
David
9000a9abd7
Merge pull request #245 from birth-software/optin-timers
Make timers opt-in
2024-06-16 17:18:20 -05:00
David Gonzalez Martin
4b80adf2fa Make timers opt-in 2024-06-16 17:15:58 -05:00
David
e2268ca74a
Merge pull request #244 from birth-software/top-level-decl-timers
Add top-level declaration timers
2024-06-16 16:43:10 -05:00
David Gonzalez Martin
adebadc573 Add top-level declaration timers 2024-06-16 16:38:56 -05:00
David
27a620fb57
Merge pull request #243 from birth-software/timers
Implement timers
2024-06-16 14:57:51 -05:00
David Gonzalez Martin
8e7e28c096 Implement timers 2024-06-16 14:54:47 -05:00
David
edab2ed2ac
Merge pull request #240 from birth-software/disable-logs
Disable logs
2024-06-15 21:35:48 -05:00
David Gonzalez Martin
87b7dc9af8 Disable logs 2024-06-15 21:33:42 -05:00
David
ba1b4669f0
Merge pull request #239 from birth-software/c-abi
C ABI implementation
2024-06-15 21:27:20 -05:00
David Gonzalez Martin
21af15ac3a wip 2024-06-15 21:25:06 -05:00
David Gonzalez Martin
5c6b050a94 C ABI implementation 2024-06-15 21:01:54 -05:00
David
4c6bc6cf8a
Merge pull request #238 from birth-software/support-comments
Support comments
2024-06-09 11:49:42 -06:00
David Gonzalez Martin
ea29b5b300 Support comments 2024-06-09 11:46:15 -06:00
David Gonzalez Martin
8f0c533b98 Remove dead code 2024-06-09 11:04:31 -06:00
David
59ac6702d9
Merge pull request #237 from birth-software/out-of-order-prototype
First out-of-order prototype
2024-06-09 10:48:28 -06:00
David Gonzalez Martin
291735086b First out-of-order prototype 2024-06-09 10:44:33 -06:00
David
5347b1f0e9
Merge pull request #236 from birth-software/start-preparing-for-c
Start preparing for C compilation
2024-06-09 08:40:56 -06:00
David Gonzalez Martin
a4c60754cd Start preparing for C compilation 2024-06-09 08:37:28 -06:00
David
0d87c928e8
Merge pull request #235 from birth-software/add-print
Add logs
2024-06-09 07:45:56 -06:00
David Gonzalez Martin
f7a37f7346 Add logs 2024-06-09 07:43:44 -06:00
David
92443cca38
Merge pull request #234 from birth-software/actually-test
Actually test in new CI
2024-06-09 07:42:13 -06:00
David Gonzalez Martin
4fbdaeaab8 Actually test in new CI 2024-06-09 07:40:03 -06:00
David
58fb05ef17
Merge pull request #233 from birth-software/rework-ci
Rework CI
2024-06-09 07:36:49 -06:00
David Gonzalez Martin
6033fdc9b9 Rework CI 2024-06-09 07:31:58 -06:00
David
90f3a01c22
Merge pull request #232 from birth-software/reenable-clang-bindings
Reenable Clang bindings
2024-06-09 07:15:12 -06:00
David Gonzalez Martin
6d43d39597 Reenable Clang bindings 2024-06-09 07:09:17 -06:00
David
b4145308a3
Merge pull request #231 from birth-software/bitfield
Implement bitfield
2024-06-08 23:47:32 -06:00
David Gonzalez Martin
fff62dd396 Implement bitfield 2024-06-08 23:43:48 -06:00
David
2826a7d59a
Merge pull request #230 from birth-software/struct
Implement struct
2024-06-08 19:24:21 -06:00
David Gonzalez Martin
455ec8cf50 Implement struct 2024-06-08 19:20:40 -06:00
David
bfe8ee5198
Merge pull request #229 from birth-software/fix-aarch64
fix aarch64-linux build
2024-06-08 14:46:43 -06:00
David Gonzalez Martin
a0e489b2dc fix aarch64-linux build 2024-06-08 14:21:29 -06:00
David
1470ca0b18
Merge pull request #228 from birth-software/di
Implement debug info
2024-06-08 11:04:46 -06:00
David Gonzalez Martin
7a18413c29 Implement debug info 2024-06-08 11:00:15 -06:00
David
d01384928f
Merge pull request #226 from birth-software/dead-code
Remove dead code
2024-06-07 18:27:22 -06:00
David Gonzalez Martin
faf8ad9212 Remove dead code 2024-06-07 18:24:51 -06:00
David
64481926f4
Merge pull request #225 from birth-software/emit-load-store
Emit load, emit store
2024-06-07 18:16:38 -06:00
David Gonzalez Martin
a5c49e6f4c Emit load, emit store 2024-06-07 18:13:47 -06:00
David
fb3494255b
Merge pull request #224 from birth-software/append-instruction
Append instruction
2024-06-07 17:56:44 -06:00
David Gonzalez Martin
2c1ed2efd8 Append instruction 2024-06-07 17:52:05 -06:00
David
19b3cb3103
Merge pull request #223 from birth-software/function-pointer
Implement function pointer
2024-06-07 13:11:36 -06:00
David Gonzalez Martin
0ee4e907b6 Implement function pointer 2024-06-07 13:08:45 -06:00
David Gonzalez Martin
6cd7c28efb Reduce some friction for global variable type 2024-06-07 11:39:55 -06:00
David
4a8b224c19
Merge pull request #222 from birth-software/pointer
Implement pointers
2024-06-07 10:55:03 -06:00
David Gonzalez Martin
3381aa0625 Implement pointers 2024-06-07 10:52:34 -06:00
David
088c8d8d5d
Merge pull request #221 from birth-software/array
Implement arrays
2024-06-07 00:14:32 -06:00
David Gonzalez Martin
cbf6829cd4 Implement arrays 2024-06-07 00:12:07 -06:00
David
c9d7dd6aa8
Merge pull request #220 from birth-software/loop-return-nocondition
Loop return no conditional
2024-06-06 22:36:21 -06:00
David Gonzalez Martin
6709fac566 Loop return no conditional 2024-06-06 22:33:37 -06:00
David
65ed3502c8
Merge pull request #219 from birth-software/loop-return-else
Loop return else
2024-06-06 22:30:41 -06:00
David Gonzalez Martin
3ad8cbe3ec Loop return else 2024-06-06 22:27:58 -06:00
David
a86f990a5f
Merge pull request #218 from birth-software/loop-return-if
Loop return if
2024-06-06 22:12:50 -06:00
David Gonzalez Martin
110b1496ef Loop return if 2024-06-06 22:10:03 -06:00
David
663e4e8a1d
Merge pull request #217 from birth-software/leading-trailing-zeroes
Implement leading and trailing zeroes
2024-06-06 21:54:43 -06:00
David Gonzalez Martin
01f3e5beae Implement leading and trailing zeroes 2024-06-06 21:51:42 -06:00
David
b549b6ed49
Merge pull request #216 from birth-software/size
Implement '#size'
2024-06-06 21:06:55 -06:00
David Gonzalez Martin
42659314ea Implement '#size' 2024-06-06 21:04:31 -06:00
David
f6bb34a354
Merge pull request #215 from birth-software/orelse
Implement 'orelse'
2024-06-06 20:52:02 -06:00
David Gonzalez Martin
ef662415d9 Implement 'orelse' 2024-06-06 20:49:45 -06:00
David
02de0f1eb3
Merge pull request #214 from birth-software/assert
Implement 'assert' builtin
2024-06-06 20:22:53 -06:00
David Gonzalez Martin
30ed5a235a Implement 'assert' builtin 2024-06-06 20:20:22 -06:00
David
9712d54290
Merge pull request #213 from birth-software/global
Implement globals
2024-06-06 18:57:50 -06:00
David Gonzalez Martin
c504cbdc73 Implement globals 2024-06-06 18:55:13 -06:00
David
62cf76b1d7
Merge pull request #212 from birth-software/rename-while-to-loop
Rename 'while' to 'loop' and imp no condition loop
2024-06-06 16:03:20 -06:00
David Gonzalez Martin
3a19ee4151 Rename 'while' to 'loop' and imp no condition loop 2024-06-06 15:57:43 -06:00
David
d998376bc0
Merge pull request #211 from birth-software/break
Implement 'break' and 'continue
2024-06-06 13:51:11 -06:00
David Gonzalez Martin
56b6443c1f Implement 'break' and 'continue 2024-06-06 13:47:14 -06:00
David
f2b1066cc6
Merge pull request #210 from birth-software/while-loop
while loop
2024-06-04 11:15:29 -06:00
David Gonzalez Martin
ae7d7f6e3b while loop 2024-06-04 11:12:00 -06:00
David Gonzalez Martin
940213c420 Disable LLVM print module at success 2024-06-03 00:34:38 -06:00
David
0292799d71
Merge pull request #209 from birth-software/even-more-ifs
Even more ifs
2024-06-03 00:34:01 -06:00
David Gonzalez Martin
d1e450233d Even more ifs 2024-06-03 00:31:24 -06:00
David
da2414b698
Merge pull request #208 from birth-software/more-if
More if
2024-06-02 21:46:06 -06:00
David Gonzalez Martin
1e5020fed1 More if 2024-06-02 21:43:31 -06:00
David
381ea47e39
Merge pull request #207 from birth-software/nested-if
Nested if
2024-06-01 11:09:41 -06:00
David Gonzalez Martin
69e01a1a7f Nested if 2024-06-01 11:07:25 -06:00
David
9731d8c893
Merge pull request #206 from birth-software/else-if
Else if
2024-06-01 10:15:37 -06:00
David Gonzalez Martin
45306355e9 Else if 2024-06-01 10:12:35 -06:00
David
bdbc33d685
Merge pull request #205 from birth-software/finalize-all-di-builders
Finalize all debug info builders
2024-06-01 09:32:50 -06:00
David Gonzalez Martin
1a49c86154 Finalize all debug info builders 2024-06-01 09:30:28 -06:00
David
4d29a31a4a
Merge pull request #204 from birth-software/one-complement
One complement
2024-06-01 09:19:54 -06:00
David Gonzalez Martin
9485bed0a7 One complement 2024-06-01 09:17:19 -06:00
David
7f56a0fe3d
Merge pull request #203 from birth-software/fn-with-args
Function with arguments
2024-05-31 23:47:03 -06:00
David Gonzalez Martin
4a91fa7e95 Function with arguments 2024-05-31 23:43:49 -06:00
David
3d1cea128a
Merge pull request #202 from birth-software/phis
Implement phis
2024-05-28 15:54:13 -06:00
David Gonzalez Martin
bcb49f3adf Implement phis 2024-05-28 15:50:55 -06:00
David
c868aa05ae
Merge pull request #201 from birth-software/improve-runner-log
Improve runner log when repetitions=1
2024-05-27 21:31:19 -06:00
David Gonzalez Martin
bcd5e52bf3 Improve runner log when repetitions=1 2024-05-27 21:28:31 -06:00
David
b0111b2a79
Merge pull request #200 from birth-software/make-no-repetitions
Make no repetitions
2024-05-27 21:19:14 -06:00
David Gonzalez Martin
6106f090aa Make no repetitions 2024-05-27 21:16:27 -06:00
David
5cbbebe29a
Merge pull request #199 from birth-software/update-to-master
Update to Zig master
2024-05-27 07:51:32 -06:00
David Gonzalez Martin
536a810b98 Update to Zig master 2024-05-27 07:47:06 -06:00
David
0c750963f6
Merge pull request #198 from birth-software/branching
Implement basic branching
2024-05-26 14:15:38 -06:00
David Gonzalez Martin
61f91d12d2 Implement basic branching 2024-05-26 14:08:23 -06:00
David
19e6246b9a
Merge pull request #197 from birth-software/div
Implement 'div'
2024-05-26 11:28:10 -06:00
David Gonzalez Martin
7902aeca97 Implement 'div' 2024-05-26 11:21:00 -06:00
David
ffb0110ea7
Merge pull request #196 from birth-software/mul
Implement 'mul'
2024-05-26 11:14:41 -06:00
David Gonzalez Martin
48db2c9265 Implement 'mul' 2024-05-26 11:10:21 -06:00
David
e66fa4f70d
Merge pull request #195 from birth-software/shifts
Implement shifts
2024-05-25 20:13:22 -06:00
David Gonzalez Martin
2f8c86a750 Implement shifts 2024-05-25 20:09:11 -06:00
David
09b6869ed0
Merge pull request #194 from birth-software/xor
Implement 'xor'
2024-05-25 18:35:15 -06:00
David Gonzalez Martin
f5291dfb9b Implement 'xor' 2024-05-25 17:50:57 -06:00
David
36d59bc372
Merge pull request #193 from birth-software/or
Implement 'or'
2024-05-25 17:44:24 -06:00
David Gonzalez Martin
074465a7e5 Implement 'or' 2024-05-25 17:40:16 -06:00
David
812e436bb7
Merge pull request #192 from birth-software/and
Implement 'and'
2024-05-25 07:56:51 -06:00
David Gonzalez Martin
ed38358ad8 Implement 'and' 2024-05-25 07:53:12 -06:00
David
43ff44f44d
Merge pull request #191 from birth-software/add-sub
Implement 'add' and 'sub'
2024-05-25 07:45:58 -06:00
David Gonzalez Martin
69e6fba3fe Implement 'add' and 'sub' 2024-05-25 07:40:28 -06:00
David
1d52b9abdc
Merge pull request #190 from birth-software/make-sleep-calls-optional
Make sleep calls optional and disabled by default
2024-05-23 20:29:48 -06:00
David Gonzalez Martin
e4dd1bb7b9 Make sleep calls optional and disabled by default 2024-05-23 20:24:28 -06:00
David
8713de03d3
Merge pull request #189 from birth-software/add-sleep-in-hot-thread-loop
Add sleep calls in hot thread loop
2024-05-23 20:22:36 -06:00
David Gonzalez Martin
a4c6f37d63 Add sleep calls in hot thread loop 2024-05-23 20:17:03 -06:00
David
d021521963
Merge pull request #188 from birth-software/const-local
Const local
2024-05-23 19:30:47 -06:00
David Gonzalez Martin
bd22f8eb80 Const local 2024-05-23 19:27:18 -06:00
David
9baae7fb24
Merge pull request #187 from birth-software/return-0
Add return 0 case
2024-05-22 08:36:26 -06:00
David Gonzalez Martin
7a69bb0686 Add return 0 case 2024-05-22 08:32:59 -06:00
David
eda0ae3448
Merge pull request #186 from birth-software/make-script-useful
Make script useful to test locally a single source
2024-05-22 08:16:00 -06:00
David Gonzalez Martin
3df904b3d3 Make script useful to test locally a single source 2024-05-22 08:10:08 -06:00
David
1152d7fb6b
Merge pull request #185 from birth-software/test-runner-for-new-compiler
Start using the existing test runner
2024-05-22 08:04:23 -06:00
David Gonzalez Martin
b28aab2dae Start using the existing test runner 2024-05-22 08:00:01 -06:00
David
ac95126fce
Merge pull request #184 from birth-software/better-handle-thread-objects
Better handle thread objects
2024-05-22 07:54:33 -06:00
David Gonzalez Martin
d0039ec494 Better handle thread objects 2024-05-22 07:40:52 -06:00
David
d9799035ef
Merge pull request #182 from birth-software/thread-compiler
Rewrite and thread compiler
2024-05-21 19:36:36 -06:00
David Gonzalez Martin
cd2316f7ee Rewrite and thread compiler 2024-05-21 19:20:34 -06:00
65 changed files with 11383 additions and 6307 deletions

View File

@ -8,6 +8,11 @@ on:
schedule: schedule:
- cron: "0 0 * * *" - cron: "0 0 * * *"
env:
NAT_LLVM_VERSION: 18
NAT_ZIG_GENERIC_COMMAND: zig build -Dthird_party_ci=true
NAT_ZIG_TEST_GENERIC_COMMAND: zig build test -Dthird_party_ci=true
TIMEOUT_MINUTES: 15
jobs: jobs:
linux-gnu: linux-gnu:
runs-on: ubuntu-latest runs-on: ubuntu-latest
@ -15,13 +20,55 @@ jobs:
steps: steps:
- name: Checkout - name: Checkout
uses: actions/checkout@v4 uses: actions/checkout@v4
- name: Build and test - name: Set Zig up mlugg/setup-zig@v1
run: ./ci/linux_gnu_runner.sh uses: mlugg/setup-zig@v1
with:
version: master
- name: Set up LLVM
run: |
wget https://apt.llvm.org/llvm.sh
chmod +x llvm.sh
sudo ./llvm.sh $NAT_LLVM_VERSION all
sudo apt install liblld-$NAT_LLVM_VERSION-dev libclang-$NAT_LLVM_VERSION-dev liblld-$NAT_LLVM_VERSION ninja-build cmake -y
- name: Build
run: |
set -ex
$NAT_ZIG_GENERIC_COMMAND -Doptimize=Debug
$NAT_ZIG_GENERIC_COMMAND -Doptimize=ReleaseSafe
$NAT_ZIG_GENERIC_COMMAND -Doptimize=ReleaseSmall
$NAT_ZIG_GENERIC_COMMAND -Doptimize=ReleaseFast
- name: Test
run: |
set -ex
$NAT_ZIG_TEST_GENERIC_COMMAND -Doptimize=Debug
$NAT_ZIG_TEST_GENERIC_COMMAND -Doptimize=ReleaseSafe
$NAT_ZIG_TEST_GENERIC_COMMAND -Doptimize=ReleaseSmall
$NAT_ZIG_TEST_GENERIC_COMMAND -Doptimize=ReleaseFast
macos: macos:
runs-on: macos-latest runs-on: macos-latest
timeout-minutes: 15 timeout-minutes: 15
steps: steps:
- name: Checkout - name: Checkout
uses: actions/checkout@v4 uses: actions/checkout@v4
- name: Build and test - name: Set Zig up mlugg/setup-zig@v1
run: ./ci/macos_runner.sh uses: mlugg/setup-zig@v1
with:
version: master
- name: Set up LLVM
run: |
brew update
brew install llvm@$NAT_LLVM_VERSION ninja
- name: Build
run: |
set -ex
$NAT_ZIG_GENERIC_COMMAND -Doptimize=Debug
$NAT_ZIG_GENERIC_COMMAND -Doptimize=ReleaseSafe
$NAT_ZIG_GENERIC_COMMAND -Doptimize=ReleaseSmall
$NAT_ZIG_GENERIC_COMMAND -Doptimize=ReleaseFast
- name: Test
run: |
set -ex
$NAT_ZIG_TEST_GENERIC_COMMAND -Doptimize=Debug
$NAT_ZIG_TEST_GENERIC_COMMAND -Doptimize=ReleaseSafe
$NAT_ZIG_TEST_GENERIC_COMMAND -Doptimize=ReleaseSmall
$NAT_ZIG_TEST_GENERIC_COMMAND -Doptimize=ReleaseFast

1
.gitignore vendored
View File

@ -1,3 +1,4 @@
.zig-cache/
zig-cache/ zig-cache/
zig-out/ zig-out/
nat/ nat/

2
.vscode/launch.json vendored
View File

@ -12,7 +12,7 @@
"args": [ "args": [
"exe", "exe",
"-main_source_file", "-main_source_file",
"test/build/c-abi/main.nat", "retest/standalone/first/main.nat"
], ],
"cwd": "${workspaceFolder}", "cwd": "${workspaceFolder}",
}, },

3
TODOLIST Normal file
View File

@ -0,0 +1,3 @@
bitstruct
c abi
for loops

View File

@ -2752,19 +2752,6 @@ pub fn argsCopyZ(arena: *Arena, args: []const []const u8) ![:null]?[*:0]u8 {
return result[0..args.len :null]; return result[0..args.len :null];
} }
extern "c" fn NativityLLVMArchiverMain(argc: c_int, argv: [*:null]?[*:0]u8) c_int;
fn arMain(arena: *Arena, arguments: []const []const u8) !u8 {
const argv = try argsCopyZ(arena, arguments);
const exit_code = NativityLLVMArchiverMain(@as(c_int, @intCast(arguments.len)), argv.ptr);
return @as(u8, @bitCast(@as(i8, @truncate(exit_code))));
}
extern "c" fn NativityClangMain(argc: c_int, argv: [*:null]?[*:0]u8) c_int;
pub fn clangMain(arena: *Arena, arguments: []const []const u8) !u8 {
const argv = try argsCopyZ(arena, arguments);
const exit_code = NativityClangMain(@as(c_int, @intCast(arguments.len)), argv.ptr);
return @as(u8, @bitCast(@as(i8, @truncate(exit_code))));
}
const ExecutableOptions = struct { const ExecutableOptions = struct {
is_test: bool, is_test: bool,
@ -2838,46 +2825,6 @@ pub fn buildExecutable(context: *const Context, arguments: []const []const u8, o
} else { } else {
reportUnterminatedArgumentError(current_argument); reportUnterminatedArgumentError(current_argument);
} }
} else if (byte_equal(current_argument, "-log")) {
if (i + 1 != arguments.len) {
i += 1;
// var log_argument_iterator = std.mem.splitScalar(u8, span(arguments[i]), ',');
//
// while (log_argument_iterator.next()) |log_argument| {
// var log_argument_splitter = std.mem.splitScalar(u8, log_argument, '.');
// const log_scope_candidate = log_argument_splitter.next() orelse unreachable;
// var recognized_scope = false;
//
// inline for (@typeInfo(LoggerScope).Enum.fields) |logger_scope_enum_field| {
// const log_scope = @field(LoggerScope, logger_scope_enum_field.name);
//
// if (byte_equal(@tagName(log_scope), log_scope_candidate)) {
// const LogScope = getLoggerScopeType(log_scope);
//
// if (log_argument_splitter.next()) |particular_log_candidate| {
// var recognized_particular = false;
// inline for (@typeInfo(LogScope.Logger).Enum.fields) |particular_log_field| {
// const particular_log = @field(LogScope.Logger, particular_log_field.name);
//
// if (byte_equal(particular_log_candidate, @tagName(particular_log))) {
// LogScope.Logger.bitset.setPresent(particular_log, true);
// recognized_particular = true;
// }
// } else if (!recognized_particular) @panic("Unrecognized particular log"); //std.debug.panic("Unrecognized particular log \"{s}\" in scope {s}", .{ particular_log_candidate, @tagName(log_scope) });
// } else {
// // LogScope.Logger.bitset = @TypeOf(LogScope.Logger.bitset).initFull();
// }
//
// logger_bitset.setPresent(log_scope, true);
//
// recognized_scope = true;
// }
// } else if (!recognized_scope) @panic("Unrecognized particular log"); //std.debug.panic("Unrecognized log scope: {s}", .{log_scope_candidate});
// }
} else {
reportUnterminatedArgumentError(current_argument);
}
} else if (byte_equal(current_argument, "-parse")) { } else if (byte_equal(current_argument, "-parse")) {
if (i + 1 != arguments.len) { if (i + 1 != arguments.len) {
i += 1; i += 1;
@ -17669,7 +17616,9 @@ pub const Unit = struct {
return unit.importPackage(context, package); return unit.importPackage(context, package);
} }
const ends_with_nat = import_name.len >= 4 and @as(u32, @bitCast(import_name[import_name.len - 4 ..][0..4].*)) == @as(u32, @bitCast(@as([*]const u8, ".nat")[0..4].*)); const nat_ending = ".nat";
const nat_ending_len = nat_ending.len;
const ends_with_nat = import_name.len >= 4 and @as(u32, @bitCast(import_name[import_name.len - nat_ending_len ..][0..nat_ending_len].*)) == @as(u32, @bitCast(@as([*]const u8, ".nat")[0..nat_ending_len].*));
if (!ends_with_nat) { if (!ends_with_nat) {
unreachable; unreachable;
} }

View File

@ -76,6 +76,8 @@ pub const LLVM = struct {
nounwind: *Attribute, nounwind: *Attribute,
inreg: *Attribute, inreg: *Attribute,
@"noalias": *Attribute, @"noalias": *Attribute,
zero_extend: *Attribute,
sign_extend: *Attribute,
}; };
pub const Linkage = enum(c_uint) { pub const Linkage = enum(c_uint) {
@ -141,7 +143,6 @@ pub const LLVM = struct {
const createConditionalBranch = bindings.NativityLLVMBuilderCreateConditionalBranch; const createConditionalBranch = bindings.NativityLLVMBuilderCreateConditionalBranch;
const createSwitch = bindings.NativityLLVMBuilderCreateSwitch; const createSwitch = bindings.NativityLLVMBuilderCreateSwitch;
const createGEP = bindings.NativityLLVMBuilderCreateGEP; const createGEP = bindings.NativityLLVMBuilderCreateGEP;
const createStructGEP = bindings.NativityLLVMBuilderCreateStructGEP;
const createICmp = bindings.NativityLLVMBuilderCreateICmp; const createICmp = bindings.NativityLLVMBuilderCreateICmp;
const createLoad = bindings.NativityLLVMBuilderCreateLoad; const createLoad = bindings.NativityLLVMBuilderCreateLoad;
const createMultiply = bindings.NativityLLVMBuilderCreateMultiply; const createMultiply = bindings.NativityLLVMBuilderCreateMultiply;
@ -167,6 +168,7 @@ pub const LLVM = struct {
const getInsertBlock = bindings.NativityLLVMBuilderGetInsertBlock; const getInsertBlock = bindings.NativityLLVMBuilderGetInsertBlock;
const isCurrentBlockTerminated = bindings.NativityLLVMBuilderIsCurrentBlockTerminated; const isCurrentBlockTerminated = bindings.NativityLLVMBuilderIsCurrentBlockTerminated;
const setCurrentDebugLocation = bindings.NativityLLVMBuilderSetCurrentDebugLocation; const setCurrentDebugLocation = bindings.NativityLLVMBuilderSetCurrentDebugLocation;
const setInstructionDebugLocation = bindings.NativityLLVMBuilderSetInstructionDebugLocation;
}; };
pub const DebugInfo = struct { pub const DebugInfo = struct {
@ -2417,6 +2419,8 @@ pub fn codegen(unit: *Compilation.Unit, context: *const Compilation.Context) !vo
.nounwind = llvm_context.getAttributeFromEnum(.NoUnwind, 0), .nounwind = llvm_context.getAttributeFromEnum(.NoUnwind, 0),
.inreg = llvm_context.getAttributeFromEnum(.InReg, 0), .inreg = llvm_context.getAttributeFromEnum(.InReg, 0),
.@"noalias" = llvm_context.getAttributeFromEnum(.NoAlias, 0), .@"noalias" = llvm_context.getAttributeFromEnum(.NoAlias, 0),
.sign_extend = llvm_context.getAttributeFromEnum(.SExt, 0),
.zero_extend = llvm_context.getAttributeFromEnum(.ZExt, 0),
}, },
.debug_info_file_map = try PinnedHashMap(Compilation.Debug.File.Index, *LLVM.DebugInfo.File).init(std.mem.page_size), .debug_info_file_map = try PinnedHashMap(Compilation.Debug.File.Index, *LLVM.DebugInfo.File).init(std.mem.page_size),
.debug_type_map = try PinnedHashMap(Compilation.Type.Index, *LLVM.DebugInfo.Type).init(std.mem.page_size), .debug_type_map = try PinnedHashMap(Compilation.Type.Index, *LLVM.DebugInfo.Type).init(std.mem.page_size),
@ -3424,17 +3428,6 @@ pub fn codegen(unit: *Compilation.Unit, context: *const Compilation.Context) !vo
const target_machine = target.createTargetMachine(target_triple.ptr, target_triple.len, cpu, cpu.len, features.pointer, features.length, LLVM.RelocationModel.static, code_model, is_code_model_present, codegen_optimization_level, jit) orelse unreachable; const target_machine = target.createTargetMachine(target_triple.ptr, target_triple.len, cpu, cpu.len, features.pointer, features.length, LLVM.RelocationModel.static, code_model, is_code_model_present, codegen_optimization_level, jit) orelse unreachable;
llvm.module.setTargetMachineDataLayout(target_machine); llvm.module.setTargetMachineDataLayout(target_machine);
llvm.module.setTargetTriple(target_triple.ptr, target_triple.len); llvm.module.setTargetTriple(target_triple.ptr, target_triple.len);
const file_path = unit.descriptor.executable_path;
const object_file_path = blk: {
const slice = try context.arena.new_array(u8, file_path.len + 3);
@memcpy(slice[0..file_path.len], file_path);
slice[file_path.len] = '.';
slice[file_path.len + 1] = 'o';
slice[file_path.len + 2] = 0;
const object_file_path = slice[0 .. slice.len - 1 :0];
break :blk object_file_path;
};
if (unit.descriptor.optimization != .none) { if (unit.descriptor.optimization != .none) {
const optimization_level: LLVM.OptimizationLevel = switch (unit.descriptor.optimization) { const optimization_level: LLVM.OptimizationLevel = switch (unit.descriptor.optimization) {
.none => unreachable, .none => unreachable,
@ -3448,6 +3441,17 @@ pub fn codegen(unit: *Compilation.Unit, context: *const Compilation.Context) !vo
llvm.module.runOptimizationPipeline(target_machine, optimization_level); llvm.module.runOptimizationPipeline(target_machine, optimization_level);
} }
const file_path = unit.descriptor.executable_path;
const object_file_path = blk: {
const slice = try context.arena.new_array(u8, file_path.len + 3);
@memcpy(slice[0..file_path.len], file_path);
slice[file_path.len] = '.';
slice[file_path.len + 1] = 'o';
slice[file_path.len + 2] = 0;
const object_file_path = slice[0 .. slice.len - 1 :0];
break :blk object_file_path;
};
const disable_verify = false; const disable_verify = false;
const result = llvm.module.addPassesToEmitFile(target_machine, object_file_path.ptr, object_file_path.len, LLVM.CodeGenFileType.object, disable_verify); const result = llvm.module.addPassesToEmitFile(target_machine, object_file_path.ptr, object_file_path.len, LLVM.CodeGenFileType.object, disable_verify);

View File

@ -1,6 +1,7 @@
const compiler = @import("../compiler.zig"); const compiler = @import("../compiler.zig");
const LLVM = compiler.LLVM; const LLVM = compiler.LLVM;
pub extern fn NativityLLVMInitializeAll() void;
pub extern fn NativityLLVMCreateContext() *LLVM.Context; pub extern fn NativityLLVMCreateContext() *LLVM.Context;
pub extern fn NativityLLVMCreateModule(module_name_ptr: [*]const u8, module_name_len: usize, context: *LLVM.Context) *LLVM.Module; pub extern fn NativityLLVMCreateModule(module_name_ptr: [*]const u8, module_name_len: usize, context: *LLVM.Context) *LLVM.Module;
pub extern fn NativityLLVMCreateBuilder(context: *LLVM.Context) *LLVM.Builder; pub extern fn NativityLLVMCreateBuilder(context: *LLVM.Context) *LLVM.Builder;
@ -11,6 +12,7 @@ pub extern fn NativityLLVMGetPointerType(context: *LLVM.Context, address_space:
pub extern fn NativityLLVMPointerTypeGetNull(pointer_type: *LLVM.Type.Pointer) *LLVM.Value.Constant.PointerNull; pub extern fn NativityLLVMPointerTypeGetNull(pointer_type: *LLVM.Type.Pointer) *LLVM.Value.Constant.PointerNull;
pub extern fn NativityLLVMGetArrayType(element_type: *LLVM.Type, element_count: u64) *LLVM.Type.Array; pub extern fn NativityLLVMGetArrayType(element_type: *LLVM.Type, element_count: u64) *LLVM.Type.Array;
pub extern fn NativityLLVMGetStructType(context: *LLVM.Context, type_ptr: [*]const *LLVM.Type, type_count: usize, is_packed: bool) *LLVM.Type.Struct; pub extern fn NativityLLVMGetStructType(context: *LLVM.Context, type_ptr: [*]const *LLVM.Type, type_count: usize, is_packed: bool) *LLVM.Type.Struct;
pub extern fn NativityLLVMCreateStructType(context: *LLVM.Context, type_pointer: [*]const *LLVM.Type, type_count: usize, name_pointer: [*]const u8, name_length: usize, is_packed: bool) *LLVM.Type.Struct;
pub extern fn NativityLLVMConstantStruct(struct_type: *LLVM.Type.Struct, constant_ptr: [*]const *LLVM.Value.Constant, constant_count: usize) *LLVM.Value.Constant; pub extern fn NativityLLVMConstantStruct(struct_type: *LLVM.Type.Struct, constant_ptr: [*]const *LLVM.Value.Constant, constant_count: usize) *LLVM.Value.Constant;
pub extern fn NativityLLVMModuleGetFunction(module: *LLVM.Module, name_ptr: [*]const u8, name_len: usize) ?*LLVM.Value.Constant.Function; pub extern fn NativityLLVMModuleGetFunction(module: *LLVM.Module, name_ptr: [*]const u8, name_len: usize) ?*LLVM.Value.Constant.Function;
pub extern fn NativityLLVModuleCreateFunction(module: *LLVM.Module, function_type: *LLVM.Type.Function, linkage: LLVM.Linkage, address_space: c_uint, name_ptr: [*]const u8, name_len: usize) *LLVM.Value.Constant.Function; pub extern fn NativityLLVModuleCreateFunction(module: *LLVM.Module, function_type: *LLVM.Type.Function, linkage: LLVM.Linkage, address_space: c_uint, name_ptr: [*]const u8, name_len: usize) *LLVM.Value.Constant.Function;
@ -23,6 +25,7 @@ pub extern fn NativityLLVMDebugInfoBuilderCreateLexicalBlock(builder: *LLVM.Debu
pub extern fn NativityLLVMDebugInfoBuilderCreateExpression(builder: *LLVM.DebugInfo.Builder, address: [*]const u64, length: usize) *LLVM.DebugInfo.Expression; pub extern fn NativityLLVMDebugInfoBuilderCreateExpression(builder: *LLVM.DebugInfo.Builder, address: [*]const u64, length: usize) *LLVM.DebugInfo.Expression;
pub extern fn NativityLLVMDebugInfoBuilderCreateGlobalVariableExpression(builder: *LLVM.DebugInfo.Builder, scope: *LLVM.DebugInfo.Scope, name_ptr: [*]const u8, name_len: usize, linkage_name_ptr: [*]const u8, linkage_name_len: usize, file: *LLVM.DebugInfo.File, line_number: c_uint, type: *LLVM.DebugInfo.Type, is_local_to_unit: bool, is_defined: bool, expression: ?*LLVM.DebugInfo.Expression, declaration: ?*LLVM.Metadata.Node, template_parameters: ?*LLVM.Metadata.Tuple, alignment: u32) *LLVM.DebugInfo.GlobalVariableExpression; pub extern fn NativityLLVMDebugInfoBuilderCreateGlobalVariableExpression(builder: *LLVM.DebugInfo.Builder, scope: *LLVM.DebugInfo.Scope, name_ptr: [*]const u8, name_len: usize, linkage_name_ptr: [*]const u8, linkage_name_len: usize, file: *LLVM.DebugInfo.File, line_number: c_uint, type: *LLVM.DebugInfo.Type, is_local_to_unit: bool, is_defined: bool, expression: ?*LLVM.DebugInfo.Expression, declaration: ?*LLVM.Metadata.Node, template_parameters: ?*LLVM.Metadata.Tuple, alignment: u32) *LLVM.DebugInfo.GlobalVariableExpression;
pub extern fn NativityLLVMDebugInfoGlobalVariableAddDebugInfo(global_variable: *LLVM.Value.Constant.GlobalVariable, global_variable_expression: *LLVM.DebugInfo.GlobalVariableExpression) void;
pub extern fn NativityLLVMDebugInfoBuilderCreateParameterVariable(builder: *LLVM.DebugInfo.Builder, scope: *LLVM.DebugInfo.Scope, name_ptr: [*]const u8, name_len: usize, argument_index: c_uint, file: *LLVM.DebugInfo.File, line_number: c_uint, type: *LLVM.DebugInfo.Type, always_preserve: bool, flags: LLVM.DebugInfo.Node.Flags) *LLVM.DebugInfo.LocalVariable; pub extern fn NativityLLVMDebugInfoBuilderCreateParameterVariable(builder: *LLVM.DebugInfo.Builder, scope: *LLVM.DebugInfo.Scope, name_ptr: [*]const u8, name_len: usize, argument_index: c_uint, file: *LLVM.DebugInfo.File, line_number: c_uint, type: *LLVM.DebugInfo.Type, always_preserve: bool, flags: LLVM.DebugInfo.Node.Flags) *LLVM.DebugInfo.LocalVariable;
pub extern fn NativityLLVMDebugInfoBuilderCreateAutoVariable(builder: *LLVM.DebugInfo.Builder, scope: *LLVM.DebugInfo.Scope, name_ptr: [*]const u8, name_len: usize, file: *LLVM.DebugInfo.File, line_number: c_uint, type: *LLVM.DebugInfo.Type, always_preserve: bool, flags: LLVM.DebugInfo.Node.Flags, alignment: u32) *LLVM.DebugInfo.LocalVariable; // 0 means 1 << 0 (alignment of 1) pub extern fn NativityLLVMDebugInfoBuilderCreateAutoVariable(builder: *LLVM.DebugInfo.Builder, scope: *LLVM.DebugInfo.Scope, name_ptr: [*]const u8, name_len: usize, file: *LLVM.DebugInfo.File, line_number: c_uint, type: *LLVM.DebugInfo.Type, always_preserve: bool, flags: LLVM.DebugInfo.Node.Flags, alignment: u32) *LLVM.DebugInfo.LocalVariable; // 0 means 1 << 0 (alignment of 1)
pub extern fn NativityLLVMDebugInfoBuilderInsertDeclare(builder: *LLVM.DebugInfo.Builder, pointer: *LLVM.Value, local_variable: *LLVM.DebugInfo.LocalVariable, context: *LLVM.Context, line: c_uint, column: c_uint, scope: *LLVM.DebugInfo.Scope, basic_block: *LLVM.Value.BasicBlock) *LLVM.Value.Instruction; pub extern fn NativityLLVMDebugInfoBuilderInsertDeclare(builder: *LLVM.DebugInfo.Builder, pointer: *LLVM.Value, local_variable: *LLVM.DebugInfo.LocalVariable, context: *LLVM.Context, line: c_uint, column: c_uint, scope: *LLVM.DebugInfo.Scope, basic_block: *LLVM.Value.BasicBlock) *LLVM.Value.Instruction;
@ -35,7 +38,9 @@ pub extern fn NativityLLVMDebugInfoBuilderCreateEnumerationType(builder: *LLVM.D
pub extern fn NativityLLVMDebugInfoBuilderCreateEnumerator(builder: *LLVM.DebugInfo.Builder, name_ptr: [*]const u8, name_len: usize, value: u64, is_unsigned: bool) *LLVM.DebugInfo.Type.Enumerator; pub extern fn NativityLLVMDebugInfoBuilderCreateEnumerator(builder: *LLVM.DebugInfo.Builder, name_ptr: [*]const u8, name_len: usize, value: u64, is_unsigned: bool) *LLVM.DebugInfo.Type.Enumerator;
pub extern fn NativityLLVMDebugInfoBuilderCreateReplaceableCompositeType(builder: *LLVM.DebugInfo.Builder, tag: c_uint, name_ptr: [*]const u8, name_len: usize, scope: ?*LLVM.DebugInfo.Scope, file: ?*LLVM.DebugInfo.File, line: c_uint) *LLVM.DebugInfo.Type.Composite; pub extern fn NativityLLVMDebugInfoBuilderCreateReplaceableCompositeType(builder: *LLVM.DebugInfo.Builder, tag: c_uint, name_ptr: [*]const u8, name_len: usize, scope: ?*LLVM.DebugInfo.Scope, file: ?*LLVM.DebugInfo.File, line: c_uint) *LLVM.DebugInfo.Type.Composite;
pub extern fn NativityLLVMDebugInfoBuilderCreateMemberType(builder: *LLVM.DebugInfo.Builder, scope: ?*LLVM.DebugInfo.Scope, name_ptr: [*]const u8, name_len: usize, file: ?*LLVM.DebugInfo.File, line_number: c_uint, bit_size: u64, alignment: u32, bit_offset: u64, flags: LLVM.DebugInfo.Node.Flags, type: *LLVM.DebugInfo.Type) *LLVM.DebugInfo.Type.Derived; pub extern fn NativityLLVMDebugInfoBuilderCreateMemberType(builder: *LLVM.DebugInfo.Builder, scope: ?*LLVM.DebugInfo.Scope, name_ptr: [*]const u8, name_len: usize, file: ?*LLVM.DebugInfo.File, line_number: c_uint, bit_size: u64, alignment: u32, bit_offset: u64, flags: LLVM.DebugInfo.Node.Flags, type: *LLVM.DebugInfo.Type) *LLVM.DebugInfo.Type.Derived;
pub extern fn NativityLLVMDebugInfoBuilderCreateBitfieldMemberType(builder: *LLVM.DebugInfo.Builder, scope: *LLVM.DebugInfo.Scope, name_pointer: [*]const u8, name_len: usize, file: *LLVM.DebugInfo.File, line_number: c_uint, bit_size: u64, bit_offset: u64, storage_bit_offset: u64, flags: LLVM.DebugInfo.Node.Flags, type: *LLVM.DebugInfo.Type) *LLVM.DebugInfo.Type.Derived;
pub extern fn NativityLLVMDebugInfoBuilderCompositeTypeReplaceTypes(builder: *LLVM.DebugInfo.Builder, type: *LLVM.DebugInfo.Type.Composite, element_type_ptr: [*]const *LLVM.DebugInfo.Type, element_type_count: usize) void; pub extern fn NativityLLVMDebugInfoBuilderCompositeTypeReplaceTypes(builder: *LLVM.DebugInfo.Builder, type: *LLVM.DebugInfo.Type.Composite, element_type_ptr: [*]const *LLVM.DebugInfo.Type, element_type_count: usize) void;
pub extern fn NativityLLLVMDITypeGetName(type: *LLVM.DebugInfo.Type, name_pointer: *[*]const u8, name_length: *usize) void;
pub extern fn NativityLLLVMDITypeIsResolved(type: *LLVM.DebugInfo.Type) bool; pub extern fn NativityLLLVMDITypeIsResolved(type: *LLVM.DebugInfo.Type) bool;
pub extern fn NativityLLVMDebugInfoBuilderFinalizeSubprogram(builder: *LLVM.DebugInfo.Builder, subprogram: *LLVM.DebugInfo.Subprogram, function: *LLVM.Value.Constant.Function) void; pub extern fn NativityLLVMDebugInfoBuilderFinalizeSubprogram(builder: *LLVM.DebugInfo.Builder, subprogram: *LLVM.DebugInfo.Subprogram, function: *LLVM.Value.Constant.Function) void;
pub extern fn NativityLLVMDebugInfoBuilderFinalize(builder: *LLVM.DebugInfo.Builder) void; pub extern fn NativityLLVMDebugInfoBuilderFinalize(builder: *LLVM.DebugInfo.Builder) void;
@ -47,8 +52,11 @@ pub extern fn NativityLLVMBasicBlockRemoveFromParent(basic_block: *LLVM.Value.Ba
pub extern fn NativityLLVMBuilderSetInsertPoint(builder: *LLVM.Builder, basic_block: *LLVM.Value.BasicBlock) void; pub extern fn NativityLLVMBuilderSetInsertPoint(builder: *LLVM.Builder, basic_block: *LLVM.Value.BasicBlock) void;
pub extern fn NativityLLVMBuilderGetInsertBlock(builder: *LLVM.Builder) *LLVM.Value.BasicBlock; pub extern fn NativityLLVMBuilderGetInsertBlock(builder: *LLVM.Builder) *LLVM.Value.BasicBlock;
pub extern fn NativityLLVMBuilderSetCurrentDebugLocation(builder: *LLVM.Builder, context: *LLVM.Context, line: c_uint, column: c_uint, scope: *LLVM.DebugInfo.Scope, function: *LLVM.Value.Constant.Function) void; pub extern fn NativityLLVMBuilderSetCurrentDebugLocation(builder: *LLVM.Builder, context: *LLVM.Context, line: c_uint, column: c_uint, scope: *LLVM.DebugInfo.Scope, function: *LLVM.Value.Constant.Function) void;
pub extern fn NativityLLVMBuilderClearCurrentDebugLocation(builder: *LLVM.Builder) void;
pub extern fn NativityLLVMBuilderSetInstructionDebugLocation(builder: *LLVM.Builder, instruction: *LLVM.Value.Instruction) void;
pub extern fn NativityLLVMValueSetName(value: *LLVM.Value, name_ptr: [*]const u8, name_len: usize) void; pub extern fn NativityLLVMValueSetName(value: *LLVM.Value, name_ptr: [*]const u8, name_len: usize) void;
pub extern fn NativityLLVMValueGetType(value: *LLVM.Value) *LLVM.Type; pub extern fn NativityLLVMValueGetType(value: *LLVM.Value) *LLVM.Type;
pub extern fn NativityLLVMValueGetContext(value: *LLVM.Value) *LLVM.Context;
pub extern fn NativityLLVMArgumentGetIndex(argument: *LLVM.Value.Argument) c_uint; pub extern fn NativityLLVMArgumentGetIndex(argument: *LLVM.Value.Argument) c_uint;
pub extern fn NativityLLVMFunctionGetArguments(function: *LLVM.Value.Constant.Function, argument_ptr: [*]*LLVM.Value.Argument, argument_len: *usize) void; pub extern fn NativityLLVMFunctionGetArguments(function: *LLVM.Value.Constant.Function, argument_ptr: [*]*LLVM.Value.Argument, argument_len: *usize) void;
pub extern fn NativityLLVMFunctionGetArgument(function: *LLVM.Value.Constant.Function, index: c_uint) *LLVM.Value.Argument; pub extern fn NativityLLVMFunctionGetArgument(function: *LLVM.Value.Constant.Function, index: c_uint) *LLVM.Value.Argument;
@ -64,6 +72,7 @@ pub extern fn NativityLLVMGetConstantArray(array_type: *LLVM.Type.Array, value_p
pub extern fn NativityLLVMGetConstantStruct(struct_type: *LLVM.Type.Struct, constant_ptr: [*]const *LLVM.Value.Constant, constant_len: usize) *LLVM.Value.Constant; pub extern fn NativityLLVMGetConstantStruct(struct_type: *LLVM.Type.Struct, constant_ptr: [*]const *LLVM.Value.Constant, constant_len: usize) *LLVM.Value.Constant;
pub extern fn NativityLLVMConstantToInt(constant: *LLVM.Value.Constant) ?*LLVM.Value.Constant.Int; pub extern fn NativityLLVMConstantToInt(constant: *LLVM.Value.Constant) ?*LLVM.Value.Constant.Int;
pub extern fn NativityLLVMBuilderCreateICmp(builder: *LLVM.Builder, integer_comparison: LLVM.Value.Instruction.ICmp.Kind, left: *LLVM.Value, right: *LLVM.Value, name_ptr: [*]const u8, name_len: usize) *LLVM.Value; pub extern fn NativityLLVMBuilderCreateICmp(builder: *LLVM.Builder, integer_comparison: LLVM.Value.Instruction.ICmp.Kind, left: *LLVM.Value, right: *LLVM.Value, name_ptr: [*]const u8, name_len: usize) *LLVM.Value;
pub extern fn NativityLLVMBuilderCreateIsNotNull(builder: *LLVM.Builder, value: *LLVM.Value, name_ptr: [*]const u8, name_len: usize) *LLVM.Value;
pub extern fn NativityLLVMBuilderCreateLoad(builder: *LLVM.Builder, type: *LLVM.Type, value: *LLVM.Value, is_volatile: bool, name_ptr: [*]const u8, name_len: usize, alignment: u32) *LLVM.Value.Instruction.Load; pub extern fn NativityLLVMBuilderCreateLoad(builder: *LLVM.Builder, type: *LLVM.Type, value: *LLVM.Value, is_volatile: bool, name_ptr: [*]const u8, name_len: usize, alignment: u32) *LLVM.Value.Instruction.Load;
pub extern fn NativityLLVMBuilderCreateRet(builder: *LLVM.Builder, value: ?*LLVM.Value) *LLVM.Value.Instruction.Ret; pub extern fn NativityLLVMBuilderCreateRet(builder: *LLVM.Builder, value: ?*LLVM.Value) *LLVM.Value.Instruction.Ret;
pub extern fn NativityLLVMBuilderCreateCast(builder: *LLVM.Builder, cast_type: LLVM.Value.Instruction.Cast.Type, value: *LLVM.Value, type: *LLVM.Type, name_ptr: [*]const u8, name_len: usize) *LLVM.Value; pub extern fn NativityLLVMBuilderCreateCast(builder: *LLVM.Builder, cast_type: LLVM.Value.Instruction.Cast.Type, value: *LLVM.Value, type: *LLVM.Type, name_ptr: [*]const u8, name_len: usize) *LLVM.Value;
@ -73,6 +82,7 @@ pub extern fn NativityLLVMContextGetAttributeFromType(context: *LLVM.Context, at
pub extern fn NativityLLVMContextGetAttributeSet(context: *LLVM.Context, attribute_ptr: ?[*]const *LLVM.Attribute, attribute_count: usize) *const LLVM.Attribute.Set; pub extern fn NativityLLVMContextGetAttributeSet(context: *LLVM.Context, attribute_ptr: ?[*]const *LLVM.Attribute, attribute_count: usize) *const LLVM.Attribute.Set;
pub extern fn NativityLLVMFunctionSetAttributes(function: *LLVM.Value.Constant.Function, context: *LLVM.Context, function_attributes: *const LLVM.Attribute.Set, return_attributes: *const LLVM.Attribute.Set, parameter_attribute_set_ptr: [*]const *const LLVM.Attribute.Set, parameter_attribute_set_count: usize) void; pub extern fn NativityLLVMFunctionSetAttributes(function: *LLVM.Value.Constant.Function, context: *LLVM.Context, function_attributes: *const LLVM.Attribute.Set, return_attributes: *const LLVM.Attribute.Set, parameter_attribute_set_ptr: [*]const *const LLVM.Attribute.Set, parameter_attribute_set_count: usize) void;
pub extern fn NativityLLVMCallSetAttributes(call: *LLVM.Value.Instruction.Call, context: *LLVM.Context, function_attributes: *const LLVM.Attribute.Set, return_attributes: *const LLVM.Attribute.Set, parameter_attribute_set_ptr: [*]const *const LLVM.Attribute.Set, parameter_attribute_set_count: usize) void; pub extern fn NativityLLVMCallSetAttributes(call: *LLVM.Value.Instruction.Call, context: *LLVM.Context, function_attributes: *const LLVM.Attribute.Set, return_attributes: *const LLVM.Attribute.Set, parameter_attribute_set_ptr: [*]const *const LLVM.Attribute.Set, parameter_attribute_set_count: usize) void;
pub extern fn NativityLLVMGlobalObjectSetAlignment(global_object: *LLVM.Value.Constant.GlobalObject, alignment: u32) void;
// pub extern fn NativityLLVMFunctionAddAttributeKey(builder: *LLVM.Value.Constant.Function, attribute_key: LLVM.Attribute) void; // pub extern fn NativityLLVMFunctionAddAttributeKey(builder: *LLVM.Value.Constant.Function, attribute_key: LLVM.Attribute) void;
pub extern fn NativityLLVMGetVoidType(context: *LLVM.Context) *LLVM.Type; pub extern fn NativityLLVMGetVoidType(context: *LLVM.Context) *LLVM.Type;
pub extern fn NativityLLVMGetInlineAssembly(function_type: *LLVM.Type.Function, assembly_ptr: [*]const u8, assembly_len: usize, constraints_ptr: [*]const u8, constrains_len: usize, has_side_effects: bool, is_align_stack: bool, dialect: LLVM.Value.InlineAssembly.Dialect, can_throw: bool) *LLVM.Value.InlineAssembly; pub extern fn NativityLLVMGetInlineAssembly(function_type: *LLVM.Type.Function, assembly_ptr: [*]const u8, assembly_len: usize, constraints_ptr: [*]const u8, constrains_len: usize, has_side_effects: bool, is_align_stack: bool, dialect: LLVM.Value.InlineAssembly.Dialect, can_throw: bool) *LLVM.Value.InlineAssembly;
@ -96,7 +106,6 @@ pub extern fn NativityLLVMBuilderCreateXor(builder: *LLVM.Builder, left: *LLVM.V
pub extern fn NativityLLVMBuilderCreateAnd(builder: *LLVM.Builder, left: *LLVM.Value, right: *LLVM.Value, name_ptr: [*]const u8, name_len: usize) *LLVM.Value; pub extern fn NativityLLVMBuilderCreateAnd(builder: *LLVM.Builder, left: *LLVM.Value, right: *LLVM.Value, name_ptr: [*]const u8, name_len: usize) *LLVM.Value;
pub extern fn NativityLLVMBuilderCreateOr(builder: *LLVM.Builder, left: *LLVM.Value, right: *LLVM.Value, name_ptr: [*]const u8, name_len: usize) *LLVM.Value; pub extern fn NativityLLVMBuilderCreateOr(builder: *LLVM.Builder, left: *LLVM.Value, right: *LLVM.Value, name_ptr: [*]const u8, name_len: usize) *LLVM.Value;
pub extern fn NativityLLVMBuilderCreateGEP(builder: *LLVM.Builder, type: *LLVM.Type, pointer: *LLVM.Value, index_ptr: [*]const *LLVM.Value, index_count: usize, name_ptr: [*]const u8, name_len: usize, in_bounds: bool) *LLVM.Value; pub extern fn NativityLLVMBuilderCreateGEP(builder: *LLVM.Builder, type: *LLVM.Type, pointer: *LLVM.Value, index_ptr: [*]const *LLVM.Value, index_count: usize, name_ptr: [*]const u8, name_len: usize, in_bounds: bool) *LLVM.Value;
pub extern fn NativityLLVMBuilderCreateStructGEP(builder: *LLVM.Builder, type: *LLVM.Type, pointer: *LLVM.Value, index: c_uint, name_ptr: [*]const u8, name_len: usize) *LLVM.Value;
pub extern fn NativityLLVMBuilderCreateBranch(builder: *LLVM.Builder, basic_block: *LLVM.Value.BasicBlock) *LLVM.Value.Instruction.Branch; pub extern fn NativityLLVMBuilderCreateBranch(builder: *LLVM.Builder, basic_block: *LLVM.Value.BasicBlock) *LLVM.Value.Instruction.Branch;
pub extern fn NativityLLVMBuilderCreateConditionalBranch(builder: *LLVM.Builder, condition: *LLVM.Value, true_block: *LLVM.Value.BasicBlock, false_block: *LLVM.Value.BasicBlock, branch_weights: ?*LLVM.Metadata.Node, unpredictable: ?*LLVM.Metadata.Node) *LLVM.Value.Instruction.Branch; pub extern fn NativityLLVMBuilderCreateConditionalBranch(builder: *LLVM.Builder, condition: *LLVM.Value, true_block: *LLVM.Value.BasicBlock, false_block: *LLVM.Value.BasicBlock, branch_weights: ?*LLVM.Metadata.Node, unpredictable: ?*LLVM.Metadata.Node) *LLVM.Value.Instruction.Branch;
pub extern fn NativityLLVMBuilderCreateSwitch(builder: *LLVM.Builder, condition: *LLVM.Value, default_block: ?*LLVM.Value.BasicBlock, case_ptr: [*]const *LLVM.Value.Constant.Int, case_block_ptr: [*]const *LLVM.Value.BasicBlock, case_count: c_uint, branch_weights: ?*LLVM.Metadata.Node, unpredictable: ?*LLVM.Metadata.Node) *LLVM.Value.Instruction.Switch; pub extern fn NativityLLVMBuilderCreateSwitch(builder: *LLVM.Builder, condition: *LLVM.Value, default_block: ?*LLVM.Value.BasicBlock, case_ptr: [*]const *LLVM.Value.Constant.Int, case_block_ptr: [*]const *LLVM.Value.BasicBlock, case_count: c_uint, branch_weights: ?*LLVM.Metadata.Node, unpredictable: ?*LLVM.Metadata.Node) *LLVM.Value.Instruction.Switch;
@ -122,6 +131,7 @@ pub extern fn NativityLLVMGetStruct(struct_type: *LLVM.Type.Struct, constant_ptr
pub extern fn NativityLLVMValueToConstant(value: *LLVM.Value) ?*LLVM.Value.Constant; pub extern fn NativityLLVMValueToConstant(value: *LLVM.Value) ?*LLVM.Value.Constant;
pub extern fn NativityLLVMValueToFunction(value: *LLVM.Value) ?*LLVM.Value.Constant.Function; pub extern fn NativityLLVMValueToFunction(value: *LLVM.Value) ?*LLVM.Value.Constant.Function;
pub extern fn NativityLLVMValueToBasicBlock(value: *LLVM.Value) ?*LLVM.Value.BasicBlock;
pub extern fn NativityLLVMTypeIsPointer(type: *LLVM.Type) bool; pub extern fn NativityLLVMTypeIsPointer(type: *LLVM.Type) bool;
pub extern fn NativityLLVMTypeIsInteger(type: *LLVM.Type) bool; pub extern fn NativityLLVMTypeIsInteger(type: *LLVM.Type) bool;
@ -157,9 +167,6 @@ pub extern fn NativityLLVMModuleSetTargetMachineDataLayout(module: *LLVM.Module,
pub extern fn NativityLLVMModuleSetTargetTriple(module: *LLVM.Module, target_triple_ptr: [*]const u8, target_triple_len: usize) void; pub extern fn NativityLLVMModuleSetTargetTriple(module: *LLVM.Module, target_triple_ptr: [*]const u8, target_triple_len: usize) void;
pub extern fn NativityLLVMTypeAssertEqual(a: *LLVM.Type, b: *LLVM.Type) void; pub extern fn NativityLLVMTypeAssertEqual(a: *LLVM.Type, b: *LLVM.Type) void;
pub extern fn LLVMCreateMemoryBufferWithMemoryRange(InputData: [*]const u8, InputDataLength: usize, BufferName: ?[*:0]const u8, RequiresNullTerminator: c_int) *LLVM.MemoryBuffer;
pub extern fn LLVMParseBitcodeInContext2(context: *LLVM.Context, memory_buffer: *LLVM.MemoryBuffer, out_module: **LLVM.Module) c_int;
pub extern fn LLVMInitializeAArch64TargetInfo() void; pub extern fn LLVMInitializeAArch64TargetInfo() void;
pub extern fn LLVMInitializeAMDGPUTargetInfo() void; pub extern fn LLVMInitializeAMDGPUTargetInfo() void;
pub extern fn LLVMInitializeARMTargetInfo() void; pub extern fn LLVMInitializeARMTargetInfo() void;

File diff suppressed because it is too large Load Diff

View File

@ -70,12 +70,16 @@ pub const Arena = struct {
} }
} }
pub inline fn new(arena: *Arena, comptime T: type) !*T { pub fn align_forward(arena: *Arena, alignment: u64) void {
arena.position = std.mem.alignForward(u64, arena.position, alignment);
}
pub fn new(arena: *Arena, comptime T: type) !*T {
const result: *T = @ptrCast(@alignCast(try arena.allocate(@sizeOf(T)))); const result: *T = @ptrCast(@alignCast(try arena.allocate(@sizeOf(T))));
return result; return result;
} }
pub inline fn new_array(arena: *Arena, comptime T: type, count: usize) ![]T { pub fn new_array(arena: *Arena, comptime T: type, count: usize) ![]T {
const result: [*]T = @ptrCast(@alignCast(try arena.allocate(@sizeOf(T) * count))); const result: [*]T = @ptrCast(@alignCast(try arena.allocate(@sizeOf(T) * count)));
return result[0..count]; return result[0..count];
} }
@ -153,6 +157,7 @@ pub fn DynamicBoundedArray(comptime T: type) type {
const pinned_array_page_size = 2 * 1024 * 1024; const pinned_array_page_size = 2 * 1024 * 1024;
const pinned_array_max_size = std.math.maxInt(u32) - pinned_array_page_size; const pinned_array_max_size = std.math.maxInt(u32) - pinned_array_page_size;
const pinned_array_default_granularity = pinned_array_page_size;
const small_granularity = std.mem.page_size; const small_granularity = std.mem.page_size;
const large_granularity = 2 * 1024 * 1024; const large_granularity = 2 * 1024 * 1024;
@ -175,10 +180,6 @@ pub fn PinnedArrayAdvanced(comptime T: type, comptime MaybeIndex: ?type, comptim
const Array = @This(); const Array = @This();
pub fn clear(array: *Array) void {
array.length = 0;
}
pub fn const_slice(array: *const Array) []const T { pub fn const_slice(array: *const Array) []const T {
return array.pointer[0..array.length]; return array.pointer[0..array.length];
} }
@ -217,7 +218,7 @@ pub fn PinnedArrayAdvanced(comptime T: type, comptime MaybeIndex: ?type, comptim
const length = array.length; const length = array.length;
const size = length * @sizeOf(T); const size = length * @sizeOf(T);
const granularity_aligned_size = array.committed * granularity; const granularity_aligned_size = align_forward(size, granularity);
const new_size = size + additional * @sizeOf(T); const new_size = size + additional * @sizeOf(T);
if (granularity_aligned_size < new_size) { if (granularity_aligned_size < new_size) {
@ -257,11 +258,24 @@ pub fn PinnedArrayAdvanced(comptime T: type, comptime MaybeIndex: ?type, comptim
return ptr; return ptr;
} }
pub fn add_one(array: *Array) *T { pub fn add_many_with_capacity(array: *Array, count: u32) []T {
const index = array.length;
assert((index + count) * @sizeOf(T) < pinned_array_max_size);
array.length += count;
const ptr = array.pointer[index..][0..count];
return ptr;
}
pub fn add_one(array: *Array) *T{
array.ensure_capacity(1); array.ensure_capacity(1);
return array.add_one_with_capacity(); return array.add_one_with_capacity();
} }
pub fn add_slice(array: *Array, count: u32) []T {
array.ensure_capacity(count);
return array.add_many_with_capacity(count);
}
pub fn append_with_capacity(array: *Array, item: T) *T { pub fn append_with_capacity(array: *Array, item: T) *T {
const ptr = array.add_one_with_capacity(); const ptr = array.add_one_with_capacity();
ptr.* = item; ptr.* = item;
@ -295,6 +309,10 @@ pub fn PinnedArrayAdvanced(comptime T: type, comptime MaybeIndex: ?type, comptim
if (@intFromPtr(item) >= top) return false; if (@intFromPtr(item) >= top) return false;
return true; return true;
} }
pub fn clear(array: *@This()) void {
array.length = 0;
}
}; };
} }
@ -345,9 +363,18 @@ pub fn getIndexForType(comptime T: type, comptime E: type) type {
return Result; return Result;
} }
fn JointEnum(comptime enums: []const type, comptime backing_type: ?type) type {
_ = backing_type; // autofix
_ = enums; // autofix
return @Type(.{
.Enum = .{
},
});
}
pub const fnv_offset = 14695981039346656037;
pub const fnv_prime = 1099511628211;
pub fn my_hash(bytes: []const u8) u32 { pub fn my_hash(bytes: []const u8) u32 {
const fnv_offset = 14695981039346656037;
const fnv_prime = 1099511628211;
var result: u64 = fnv_offset; var result: u64 = fnv_offset;
for (bytes) |byte| { for (bytes) |byte| {
@ -452,28 +479,30 @@ pub fn PinnedHashMapAdvanced(comptime K: type, comptime V: type, comptime granul
} }
} }
pub fn put(map: *@This(), key: K, value: V) void { pub fn put(map: *@This(), key: K, value: V) *V {
if (map.get_pointer(key)) |value_pointer| { if (map.get_pointer(key)) |value_pointer| {
value_pointer.* = value; value_pointer.* = value;
return value_pointer;
} else { } else {
const len = map.length; const len = map.length;
map.ensure_capacity(len + 1); map.ensure_capacity(len + 1);
map.put_at_with_capacity(len, key, value); return map.put_at_with_capacity(len, key, value);
} }
} }
pub fn put_no_clobber(map: *@This(), key: K, value: V) void { pub fn put_no_clobber(map: *@This(), key: K, value: V) *V {
assert(map.get_pointer(key) == null); assert(map.get_pointer(key) == null);
const len = map.length; const len = map.length;
map.ensure_capacity(len + 1); map.ensure_capacity(len + 1);
map.put_at_with_capacity(len, key, value); return map.put_at_with_capacity(len, key, value);
} }
fn put_at_with_capacity(map: *@This(), index: u64, key: K, value: V) void { fn put_at_with_capacity(map: *@This(), index: u64, key: K, value: V) *V {
map.length += 1; map.length += 1;
assert(index < map.length); assert(index < map.length);
map.key_pointer[index] = key; map.key_pointer[index] = key;
map.value_pointer[index] = value; map.value_pointer[index] = value;
return &map.value_pointer[index];
} }
fn ensure_capacity(map: *Map, additional: u64) void { fn ensure_capacity(map: *Map, additional: u64) void {
@ -487,7 +516,7 @@ pub fn PinnedHashMapAdvanced(comptime K: type, comptime V: type, comptime granul
{ {
const key_size = length * @sizeOf(K); const key_size = length * @sizeOf(K);
const key_granularity_aligned_size = map.committed_key * granularity; const key_granularity_aligned_size = align_forward(key_size, granularity);
const key_new_size = key_size + additional * @sizeOf(K); const key_new_size = key_size + additional * @sizeOf(K);
if (key_granularity_aligned_size < key_new_size) { if (key_granularity_aligned_size < key_new_size) {
@ -502,7 +531,7 @@ pub fn PinnedHashMapAdvanced(comptime K: type, comptime V: type, comptime granul
{ {
const value_size = length * @sizeOf(V); const value_size = length * @sizeOf(V);
const value_granularity_aligned_size = map.committed_value * granularity; const value_granularity_aligned_size = align_forward(value_size, granularity);
const value_new_size = value_size + additional * @sizeOf(K); const value_new_size = value_size + additional * @sizeOf(K);
if (value_granularity_aligned_size < value_new_size) { if (value_granularity_aligned_size < value_new_size) {
@ -768,11 +797,11 @@ pub fn exit_with_error() noreturn {
pub fn read_file(arena: *Arena, directory: std.fs.Dir, file_relative_path: []const u8) []const u8 { pub fn read_file(arena: *Arena, directory: std.fs.Dir, file_relative_path: []const u8) []const u8 {
const source_file = directory.openFile(file_relative_path, .{}) catch |err| { const source_file = directory.openFile(file_relative_path, .{}) catch |err| {
const stdout = std.io.getStdOut(); const stdout = std.io.getStdOut();
stdout.writeAll("Can't find file ") catch {}; stdout.writeAll("Can't find file '") catch {};
stdout.writeAll(file_relative_path) catch {}; stdout.writeAll(file_relative_path) catch {};
// stdout.writeAll(" in directory ") catch {}; // stdout.writeAll(" in directory ") catch {};
// stdout.writeAll(file.package.directory.path) catch {}; // stdout.writeAll(file.package.directory.path) catch {};
stdout.writeAll(" for error ") catch {}; stdout.writeAll("' for error ") catch {};
stdout.writeAll(@errorName(err)) catch {}; stdout.writeAll(@errorName(err)) catch {};
@panic("Unrecoverable error"); @panic("Unrecoverable error");
}; };
@ -789,14 +818,26 @@ pub fn read_file(arena: *Arena, directory: std.fs.Dir, file_relative_path: []con
} }
pub fn self_exe_path(arena: *Arena) ![]const u8 { pub fn self_exe_path(arena: *Arena) ![]const u8 {
var buffer: [std.fs.MAX_PATH_BYTES]u8 = undefined; var buffer: [std.fs.max_path_bytes]u8 = undefined;
return try arena.duplicate_bytes(try std.fs.selfExePath(&buffer)); return try arena.duplicate_bytes(try std.fs.selfExePath(&buffer));
} }
pub fn realpath(arena: *Arena, dir: std.fs.Dir, relative_path: []const u8) ![]const u8 { pub fn realpath(arena: *Arena, dir: std.fs.Dir, relative_path: []const u8) ![]const u8 {
var buffer: [std.fs.MAX_PATH_BYTES]u8 = undefined; var buffer: [std.fs.max_path_bytes]u8 = undefined;
const stack_realpath = try dir.realpath(relative_path, &buffer); const stack_realpath = try dir.realpath(relative_path, &buffer);
const heap_realpath = try arena.new_array(u8, stack_realpath.len); const heap_realpath = try arena.new_array(u8, stack_realpath.len);
@memcpy(heap_realpath, stack_realpath); @memcpy(heap_realpath, stack_realpath);
return heap_realpath; return heap_realpath;
} }
pub fn argument_copy_zero_terminated(arena: *Arena, args: []const []const u8) ![:null]?[*:0]u8 {
var result = try arena.new_array(?[*:0]u8, args.len + 1);
result[args.len] = null;
for (args, 0..) |argument, i| {
result[i] = try arena.duplicate_bytes_zero_terminated(argument);
}
return result[0..args.len :null];
}

View File

@ -1,5 +1,7 @@
const std = @import("std"); const std = @import("std");
const assert = std.debug.assert; const assert = std.debug.assert;
const builtin = @import("builtin");
const linker = @import("linker.zig"); const linker = @import("linker.zig");
const library = @import("../library.zig"); const library = @import("../library.zig");
@ -11,7 +13,7 @@ const write = Compilation.write;
pub fn link(context: *const Compilation.Context, options: linker.Options) !void { pub fn link(context: *const Compilation.Context, options: linker.Options) !void {
assert(options.backend == .lld); assert(options.backend == .lld);
var argv = try PinnedArray([]const u8).init_with_default_granularity(); var argv = try PinnedArray([]const u8).init_with_default_granularity();
const driver_program = switch (@import("builtin").os.tag) { const driver_program = switch (builtin.os.tag) {
.windows => "lld-link", .windows => "lld-link",
.linux => "ld.lld", .linux => "ld.lld",
.macos => "ld64.lld", .macos => "ld64.lld",
@ -20,8 +22,8 @@ pub fn link(context: *const Compilation.Context, options: linker.Options) !void
_ = argv.append(driver_program); _ = argv.append(driver_program);
_ = argv.append("--error-limit=0"); _ = argv.append("--error-limit=0");
switch (@import("builtin").cpu.arch) { switch (builtin.cpu.arch) {
.aarch64 => switch (@import("builtin").os.tag) { .aarch64 => switch (builtin.os.tag) {
.linux => { .linux => {
_ = argv.append("-znow"); _ = argv.append("-znow");
_ = argv.append_slice(&.{ "-m", "aarch64linux" }); _ = argv.append_slice(&.{ "-m", "aarch64linux" });
@ -42,12 +44,12 @@ pub fn link(context: *const Compilation.Context, options: linker.Options) !void
} }
const ci = @import("configuration").ci; const ci = @import("configuration").ci;
switch (@import("builtin").os.tag) { switch (builtin.os.tag) {
.macos => { .macos => {
_ = argv.append("-dynamic"); _ = argv.append("-dynamic");
argv.append_slice(&.{ "-platform_version", "macos", "13.4.1", "13.3" }); argv.append_slice(&.{ "-platform_version", "macos", "13.4.1", "13.3" });
_ = argv.append("-arch"); _ = argv.append("-arch");
_ = argv.append(switch (@import("builtin").cpu.arch) { _ = argv.append(switch (builtin.cpu.arch) {
.aarch64 => "arm64", .aarch64 => "arm64",
else => |t| @panic(@tagName(t)), else => |t| @panic(@tagName(t)),
}); });
@ -98,7 +100,7 @@ pub fn link(context: *const Compilation.Context, options: linker.Options) !void
argv.append_slice(&.{ "-L", "/usr/lib64" }); argv.append_slice(&.{ "-L", "/usr/lib64" });
_ = argv.append("-dynamic-linker"); _ = argv.append("-dynamic-linker");
switch (@import("builtin").cpu.arch) { switch (builtin.cpu.arch) {
.x86_64 => _ = argv.append("/lib64/ld-linux-x86-64.so.2"), .x86_64 => _ = argv.append("/lib64/ld-linux-x86-64.so.2"),
.aarch64 => _ = argv.append("/lib/ld-linux-aarch64.so.1"), .aarch64 => _ = argv.append("/lib/ld-linux-aarch64.so.1"),
else => unreachable, else => unreachable,
@ -130,7 +132,7 @@ pub fn link(context: *const Compilation.Context, options: linker.Options) !void
var stdout_len: usize = 0; var stdout_len: usize = 0;
var stderr_ptr: [*]const u8 = undefined; var stderr_ptr: [*]const u8 = undefined;
var stderr_len: usize = 0; var stderr_len: usize = 0;
const result = switch (@import("builtin").os.tag) { const result = switch (builtin.os.tag) {
.linux => NativityLLDLinkELF(argv_zero_terminated.ptr, argv_zero_terminated.len, &stdout_ptr, &stdout_len, &stderr_ptr, &stderr_len), .linux => NativityLLDLinkELF(argv_zero_terminated.ptr, argv_zero_terminated.len, &stdout_ptr, &stdout_len, &stderr_ptr, &stderr_len),
.macos => NativityLLDLinkMachO(argv_zero_terminated.ptr, argv_zero_terminated.len, &stdout_ptr, &stdout_len, &stderr_ptr, &stderr_len), .macos => NativityLLDLinkMachO(argv_zero_terminated.ptr, argv_zero_terminated.len, &stdout_ptr, &stdout_len, &stderr_ptr, &stderr_len),
.windows => NativityLLDLinkCOFF(argv_zero_terminated.ptr, argv_zero_terminated.len, &stdout_ptr, &stdout_len, &stderr_ptr, &stderr_len), .windows => NativityLLDLinkCOFF(argv_zero_terminated.ptr, argv_zero_terminated.len, &stdout_ptr, &stdout_len, &stderr_ptr, &stderr_len),

View File

@ -1,8 +1,7 @@
const std = @import("std"); const std = @import("std");
const assert = std.debug.assert; const assert = std.debug.assert;
const Compilation = @import("Compilation.zig"); const builtin = @import("builtin");
pub const panic = Compilation.panic;
const library = @import("library.zig"); const library = @import("library.zig");
const byte_equal = library.byte_equal; const byte_equal = library.byte_equal;
@ -10,6 +9,7 @@ const byte_equal = library.byte_equal;
const configuration = @import("configuration"); const configuration = @import("configuration");
const editor = @import("editor.zig"); const editor = @import("editor.zig");
const compiler = @import("compiler.zig"); const compiler = @import("compiler.zig");
pub const panic = compiler.panic;
const env_detecting_libc_paths = "NATIVITY_IS_DETECTING_LIBC_PATHS"; const env_detecting_libc_paths = "NATIVITY_IS_DETECTING_LIBC_PATHS";
@ -17,59 +17,11 @@ test {
_ = library; _ = library;
} }
fn todo() noreturn {
@setCold(true);
@panic("TODO");
}
pub fn main() !void { pub fn main() !void {
if (configuration.editor) { if (configuration.editor) {
editor.main(); editor.main();
} else { } else {
compiler.make(); compiler.main();
// var arg_iterator = std.process.ArgIterator.init();
// var buffer = library.BoundedArray([]const u8, 512){};
// while (arg_iterator.next()) |argument| {
// buffer.appendAssumeCapacity(argument);
// }
// const arguments = buffer.slice();
// const context = try Compilation.createContext();
//
// if (arguments.len <= 1) {
// return error.InvalidInput;
// }
//
// if (std.process.can_execv and std.posix.getenvZ(env_detecting_libc_paths) != null) {
// todo();
// }
//
// const command = arguments[1];
// const command_arguments = arguments[2..];
//
// if (byte_equal(command, "build")) {
// try Compilation.compileBuildExecutable(context, command_arguments);
// } else if (byte_equal(command, "clang") or byte_equal(command, "-cc1") or byte_equal(command, "-cc1as")) {
// const exit_code = try Compilation.clangMain(context.arena, arguments);
// std.process.exit(exit_code);
// } else if (byte_equal(command, "cc")) {
// try Compilation.compileCSourceFile(context, command_arguments, .c);
// } else if (byte_equal(command, "c++")) {
// try Compilation.compileCSourceFile(context, command_arguments, .cpp);
// } else if (byte_equal(command, "exe")) {
// try Compilation.buildExecutable(context, command_arguments, .{
// .is_test = false,
// });
// } else if (byte_equal(command, "lib")) {
// todo();
// } else if (byte_equal(command, "obj")) {
// todo();
// } else if (byte_equal(command, "test")) {
// try Compilation.buildExecutable(context, command_arguments, .{
// .is_test = true,
// });
// } else {
// todo();
// }
} }
} }

142
build.zig
View File

@ -6,7 +6,7 @@ const os = builtin.os.tag;
fn discover_brew_prefix(b: *std.Build, library_name: []const u8) ![]const u8 { fn discover_brew_prefix(b: *std.Build, library_name: []const u8) ![]const u8 {
assert(os == .macos); assert(os == .macos);
const result = try std.ChildProcess.run(.{ const result = try std.process.Child.run(.{
.allocator = b.allocator, .allocator = b.allocator,
.argv = &.{ "brew", "--prefix", library_name }, .argv = &.{ "brew", "--prefix", library_name },
}); });
@ -29,22 +29,23 @@ pub fn build(b: *std.Build) !void {
const enable_editor = false; const enable_editor = false;
const use_editor = b.option(bool, "editor", "Use the GUI editor to play around the programming language") orelse (!is_ci and enable_editor); const use_editor = b.option(bool, "editor", "Use the GUI editor to play around the programming language") orelse (!is_ci and enable_editor);
const use_debug = b.option(bool, "use_debug", "This option enables the LLVM debug build in the development PC") orelse false; const use_debug = b.option(bool, "use_debug", "This option enables the LLVM debug build in the development PC") orelse false;
const sanitize = b.option(bool, "sanitize", "This option enables sanitizers for the compiler") orelse false;
const sleep_on_thread_hot_loops = b.option(bool, "sleep", "This option enables sleep calls on hot threaded loops") orelse false;
const static = b.option(bool, "static", "This option enables the compiler to be built statically") orelse switch (@import("builtin").os.tag) { const static = b.option(bool, "static", "This option enables the compiler to be built statically") orelse switch (@import("builtin").os.tag) {
else => false, else => use_debug,
.windows => true, .windows => true,
// .macos => true, // .macos => true,
}; };
const compiler_options = b.addOptions(); const timers = b.option(bool, "timers", "This option enables to make and print timers") orelse !is_ci and switch (optimization) {
compiler_options.addOption(bool, "print_stack_trace", print_stack_trace); .Debug => false,
compiler_options.addOption(bool, "ci", is_ci); else => true,
compiler_options.addOption(bool, "editor", use_editor); };
const fetcher = b.addExecutable(.{ const fetcher = b.addExecutable(.{
.name = "llvm_fetcher", .name = "llvm_fetcher",
.root_source_file = b.path("build/fetcher.zig"), .root_source_file = b.path("build/fetcher.zig"),
.target = native_target, .target = native_target,
.optimize = .Debug, .optimize = .Debug,
.single_threaded = true,
}); });
var target_query = b.standardTargetOptionsQueryOnly(switch (@import("builtin").os.tag) { var target_query = b.standardTargetOptionsQueryOnly(switch (@import("builtin").os.tag) {
@ -90,10 +91,10 @@ pub fn build(b: *std.Build) !void {
const cpp_files = .{ const cpp_files = .{
"src/llvm/llvm.cpp", "src/llvm/llvm.cpp",
// "src/llvm/lld.cpp", "src/llvm/lld.cpp",
// "src/llvm/clang_main.cpp", "src/llvm/clang_main.cpp",
// "src/llvm/clang_cc1.cpp", "src/llvm/clang_cc1.cpp",
// "src/llvm/clang_cc1as.cpp", "src/llvm/clang_cc1as.cpp",
// "src/llvm/ar.cpp", // "src/llvm/ar.cpp",
}; };
@ -106,21 +107,24 @@ pub fn build(b: *std.Build) !void {
"-D__STDC_FORMAT_MACROS", "-D__STDC_FORMAT_MACROS",
"-D__STDC_LIMIT_MACROS", "-D__STDC_LIMIT_MACROS",
"-D_GNU_SOURCE", "-D_GNU_SOURCE",
"-fvisibility-inlines-hidden",
"-fno-exceptions", "-fno-exceptions",
"-fno-rtti", "-fno-rtti",
"-Werror=type-limits", "-fno-stack-protector",
"-fvisibility-inlines-hidden",
"-Wno-type-limits",
"-Wno-missing-braces", "-Wno-missing-braces",
"-Wno-comment", "-Wno-comment",
}, },
}); });
compiler.root_module.addOptions("configuration", compiler_options);
compiler.formatted_panics = print_stack_trace; compiler.formatted_panics = print_stack_trace;
compiler.root_module.unwind_tables = print_stack_trace or target.result.os.tag == .windows; compiler.root_module.unwind_tables = print_stack_trace or target.result.os.tag == .windows;
compiler.root_module.omit_frame_pointer = false; compiler.root_module.omit_frame_pointer = false;
compiler.root_module.error_tracing = print_stack_trace; compiler.root_module.error_tracing = print_stack_trace;
compiler.want_lto = false; compiler.want_lto = false;
if (sanitize) {
compiler.root_module.sanitize_thread = true;
}
compiler.linkLibC(); compiler.linkLibC();
@ -365,6 +369,8 @@ pub fn build(b: *std.Build) !void {
"libclangTransformer.a", "libclangTransformer.a",
}; };
var include_paths = std.ArrayList([]const u8).init(b.allocator);
if (static or target.result.os.tag == .windows) { if (static or target.result.os.tag == .windows) {
if (target.result.os.tag == .linux) compiler.linkage = .static; if (target.result.os.tag == .linux) compiler.linkage = .static;
compiler.linkLibCpp(); compiler.linkLibCpp();
@ -409,8 +415,8 @@ pub fn build(b: *std.Build) !void {
break :blk llvm_directory.items; break :blk llvm_directory.items;
} else { } else {
break :blk switch (use_debug) { break :blk switch (use_debug) {
true => "../zig-bootstrap/out/x86_64-linux-musl-native-debug-static", true => "../zig-bootstrap/out/x86_64-linux-musl-native",
false => "../zig-bootstrap/out/x86_64-linux-musl-native-release-static", false => "../zig-bootstrap/out/x86_64-linux-musl-native",
}; };
} }
}; };
@ -424,29 +430,32 @@ pub fn build(b: *std.Build) !void {
} }
} else { } else {
compiler.linkSystemLibrary("LLVM"); compiler.linkSystemLibrary("LLVM");
// compiler.linkSystemLibrary("clang-cpp"); compiler.linkSystemLibrary("clang-cpp");
// compiler.linkSystemLibrary("lldCommon"); compiler.linkSystemLibrary("lldCommon");
// compiler.linkSystemLibrary("lldCOFF"); compiler.linkSystemLibrary("lldCOFF");
// compiler.linkSystemLibrary("lldELF"); compiler.linkSystemLibrary("lldELF");
// compiler.linkSystemLibrary("lldMachO"); compiler.linkSystemLibrary("lldMachO");
// compiler.linkSystemLibrary("lldWasm"); compiler.linkSystemLibrary("lldWasm");
// compiler.linkSystemLibrary("unwind"); // compiler.linkSystemLibrary("unwind");
// compiler.linkSystemLibrary(if (is_ci) "z" else "zlib"); compiler.linkSystemLibrary(if (is_ci or builtin.os.tag == .macos) "z" else "zlib");
// compiler.linkSystemLibrary("zstd"); compiler.linkSystemLibrary("zstd");
var llvm_prefix: []const u8 = "";
switch (target.result.os.tag) { switch (target.result.os.tag) {
.linux => { .linux => {
if (third_party_ci) { if (third_party_ci) {
compiler.addObjectFile(.{ .cwd_relative = "/lib/x86_64-linux-gnu/libstdc++.so.6" }); compiler.addObjectFile(.{ .cwd_relative = "/lib/x86_64-linux-gnu/libstdc++.so.6" });
compiler.addIncludePath(.{ .cwd_relative = "/usr/include" }); try include_paths.append("/usr/include");
compiler.addIncludePath(.{ .cwd_relative = "/usr/include/x86_64-linux-gnu" }); try include_paths.append("/usr/include" );
compiler.addIncludePath(.{ .cwd_relative = "/usr/include/c++/11" }); try include_paths.append("/usr/include/x86_64-linux-gnu" );
compiler.addIncludePath(.{ .cwd_relative = "/usr/include/x86_64-linux-gnu/c++/11" }); try include_paths.append("/usr/include/c++/11" );
compiler.addIncludePath(.{ .cwd_relative = "/usr/lib/llvm-17/include" }); try include_paths.append("/usr/include/x86_64-linux-gnu/c++/11" );
try include_paths.append("/usr/lib/llvm-18/include" );
llvm_prefix = "/usr/lib/llvm-18";
compiler.addLibraryPath(.{ .cwd_relative = "/lib/x86_64-linux-gnu" }); compiler.addLibraryPath(.{ .cwd_relative = "/lib/x86_64-linux-gnu" });
compiler.addLibraryPath(.{ .cwd_relative = "/usr/lib/llvm-17/lib" }); compiler.addLibraryPath(.{ .cwd_relative = "/usr/lib/llvm-18/lib" });
} else { } else {
const result = try std.ChildProcess.run(.{ const result = try std.process.Child.run(.{
.allocator = b.allocator, .allocator = b.allocator,
.argv = &.{ .argv = &.{
"c++", "--version", "c++", "--version",
@ -462,11 +471,15 @@ pub fn build(b: *std.Build) !void {
unreachable; unreachable;
} }
var tokenizer = std.mem.tokenize(u8, result.stdout, " "); var tokenizer = std.mem.tokenizeScalar(u8, result.stdout, ' ');
const cxx_version = while (tokenizer.next()) |chunk| { const cxx_version = while (tokenizer.next()) |chunk| {
if (std.ascii.isDigit(chunk[0])) { if (std.ascii.isDigit(chunk[0])) {
if (std.SemanticVersion.parse(chunk)) |sema_version| { if (std.SemanticVersion.parse(chunk)) |sema_version| {
break try std.fmt.allocPrint(b.allocator, "{}.{}.{}", .{sema_version.major, sema_version.minor, sema_version.patch}); break switch (builtin.cpu.arch) {
.x86_64 => try std.fmt.allocPrint(b.allocator, "{}.{}.{}", .{sema_version.major, sema_version.minor, sema_version.patch}),
.aarch64 => try std.fmt.allocPrint(b.allocator, "{}", .{sema_version.major}),
else => @compileError("Architecture not supported"),
};
} else |err| err catch {}; } else |err| err catch {};
} }
} else { } else {
@ -474,31 +487,30 @@ pub fn build(b: *std.Build) !void {
}; };
const cxx_include_base = try std.mem.concat(b.allocator, u8, &.{ "/usr/include/c++/", cxx_version }); const cxx_include_base = try std.mem.concat(b.allocator, u8, &.{ "/usr/include/c++/", cxx_version });
const cxx_include_arch = try std.mem.concat(b.allocator, u8, &.{ cxx_include_base, "/" ++ @tagName(@import("builtin").cpu.arch) ++ "-pc-linux-gnu" }); const cxx_include_arch = try std.mem.concat(b.allocator, u8, &.{ cxx_include_base, "/" ++ @tagName(builtin.cpu.arch) ++ switch (builtin.cpu.arch) {
.x86_64 => "-pc-linux-gnu",
.aarch64 => "-redhat-linux",
else => @compileError("Architecture not supported"),
}
});
compiler.addObjectFile(.{ .cwd_relative = "/usr/lib64/libstdc++.so.6" }); compiler.addObjectFile(.{ .cwd_relative = "/usr/lib64/libstdc++.so.6" });
if (use_debug) { llvm_prefix = if (use_debug) "../../local/llvm18-debug/" else "../../local/llvm18-release";
compiler.addIncludePath(.{ .cwd_relative = "../../local/llvm18-debug/include" }); try include_paths.append(try std.mem.concat(b.allocator, u8, &.{llvm_prefix, "/include"}));
} else { try include_paths.append("/usr/include");
compiler.addIncludePath(.{ .cwd_relative = "../../local/llvm18-release/include" }); try include_paths.append(cxx_include_base);
} try include_paths.append(cxx_include_arch);
compiler.addIncludePath(.{ .cwd_relative = "/usr/include" }); compiler.addLibraryPath(.{ .cwd_relative = if (use_debug) "../../local/llvm18-debug/lib" else "../../local/llvm18-release/lib" });
compiler.addIncludePath(.{ .cwd_relative = cxx_include_base });
compiler.addIncludePath(.{ .cwd_relative = cxx_include_arch });
if (use_debug) {
compiler.addLibraryPath(.{ .cwd_relative = "../../local/llvm18-debug/lib" });
} else {
compiler.addLibraryPath(.{ .cwd_relative = "../../local/llvm18-release/lib" });
}
compiler.addLibraryPath(.{ .cwd_relative = "/usr/lib64" }); compiler.addLibraryPath(.{ .cwd_relative = "/usr/lib64" });
} }
}, },
.macos => { .macos => {
compiler.linkLibCpp(); compiler.linkLibCpp();
if (discover_brew_prefix(b, "llvm@17")) |llvm_prefix| { if (discover_brew_prefix(b, "llvm@18")) |prefix| {
llvm_prefix = prefix;
const llvm_include_path = try std.mem.concat(b.allocator, u8, &.{ llvm_prefix, "/include" }); const llvm_include_path = try std.mem.concat(b.allocator, u8, &.{ llvm_prefix, "/include" });
const llvm_lib_path = try std.mem.concat(b.allocator, u8, &.{ llvm_prefix, "/lib" }); const llvm_lib_path = try std.mem.concat(b.allocator, u8, &.{ llvm_prefix, "/lib" });
compiler.addIncludePath(.{ .cwd_relative = llvm_include_path }); try include_paths.append(llvm_include_path);
compiler.addLibraryPath(.{ .cwd_relative = llvm_lib_path }); compiler.addLibraryPath(.{ .cwd_relative = llvm_lib_path });
} else |err| { } else |err| {
return err; return err;
@ -522,6 +534,12 @@ pub fn build(b: *std.Build) !void {
else => |tag| @panic(@tagName(tag)), else => |tag| @panic(@tagName(tag)),
} }
for (include_paths.items) |include_path| {
compiler.addIncludePath(.{ .cwd_relative = include_path });
}
try include_paths.append(try std.mem.concat(b.allocator, u8, &.{llvm_prefix, "/lib/clang/18/include"}));
if (use_editor) { if (use_editor) {
compiler.linkSystemLibrary("glfw"); compiler.linkSystemLibrary("glfw");
compiler.linkSystemLibrary("GL"); compiler.linkSystemLibrary("GL");
@ -545,6 +563,15 @@ pub fn build(b: *std.Build) !void {
} }
} }
const compiler_options = b.addOptions();
compiler_options.addOption(bool, "print_stack_trace", print_stack_trace);
compiler_options.addOption(bool, "ci", is_ci);
compiler_options.addOption(bool, "editor", use_editor);
compiler_options.addOption(bool, "sleep_on_thread_hot_loops", sleep_on_thread_hot_loops);
compiler_options.addOption([]const []const u8, "include_paths", include_paths.items);
compiler_options.addOption(bool, "timers", timers);
compiler.root_module.addOptions("configuration", compiler_options);
if (target.result.os.tag == .windows) { if (target.result.os.tag == .windows) {
compiler.linkSystemLibrary("ole32"); compiler.linkSystemLibrary("ole32");
compiler.linkSystemLibrary("version"); compiler.linkSystemLibrary("version");
@ -594,7 +621,6 @@ pub fn build(b: *std.Build) !void {
.root_source_file = b.path("build/test_runner.zig"), .root_source_file = b.path("build/test_runner.zig"),
.target = native_target, .target = native_target,
.optimize = optimization, .optimize = optimization,
.single_threaded = true,
}); });
b.default_step.dependOn(&test_runner.step); b.default_step.dependOn(&test_runner.step);
@ -603,10 +629,22 @@ pub fn build(b: *std.Build) !void {
b.installArtifact(test_runner); b.installArtifact(test_runner);
test_command.step.dependOn(b.getInstallStep()); test_command.step.dependOn(b.getInstallStep());
const new_test = b.addExecutable(.{
.name = "new_test",
.target = native_target,
.root_source_file = b.path("build/new_test.zig"),
.optimize = .ReleaseSmall,
});
b.default_step.dependOn(&new_test.step);
const new_test_command = b.addRunArtifact(new_test);
new_test_command.step.dependOn(b.getInstallStep());
if (b.args) |args| { if (b.args) |args| {
run_command.addArgs(args); run_command.addArgs(args);
debug_command.addArgs(args); debug_command.addArgs(args);
test_command.addArgs(args); test_command.addArgs(args);
new_test_command.addArgs(args);
} }
const run_step = b.step("run", "Test the Nativity compiler"); const run_step = b.step("run", "Test the Nativity compiler");
@ -615,7 +653,11 @@ pub fn build(b: *std.Build) !void {
debug_step.dependOn(&debug_command.step); debug_step.dependOn(&debug_command.step);
const test_step = b.step("test", "Test the Nativity compiler"); const test_step = b.step("test", "Test the Nativity compiler");
test_step.dependOn(&test_command.step); test_step.dependOn(&test_command.step);
const new_test_step = b.step("new_test", "Script to make a new test");
new_test_step.dependOn(&new_test_command.step);
const test_all = b.step("test_all", "Test all"); const test_all = b.step("test_all", "Test all");
test_all.dependOn(&test_command.step); test_all.dependOn(&test_command.step);
} }

17
build/new_test.zig Normal file
View File

@ -0,0 +1,17 @@
const std = @import("std");
pub fn main () !void {
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
const allocator = arena.allocator();
const args = try std.process.argsAlloc(allocator);
if (args.len < 2) return;
const test_name = args[1];
try std.fs.cwd().makeDir(try std.mem.concat(allocator, u8, &.{"retest/standalone/", test_name}));
try std.fs.cwd().writeFile(.{
.sub_path = try std.mem.concat(allocator, u8, &.{"retest/standalone/", test_name, "/main.nat"}),
.data =
\\fn[cc(.c)] main[export]() s32 {
\\ return 0;
\\}
});
}

View File

@ -31,37 +31,43 @@ fn collectDirectoryDirEntries(allocator: Allocator, path: []const u8) ![]const [
const bootstrap_relative_path = "zig-out/bin/nat"; const bootstrap_relative_path = "zig-out/bin/nat";
fn runStandalone(allocator: Allocator, args: struct { const Run = struct{
directory_path: []const u8, compilation_run: usize = 0,
group_name: []const u8, compilation_failure: usize = 0,
self_hosted: bool, test_run: usize = 0,
is_test: bool, test_failure: usize = 0,
fn add(run: *Run, other: Run) void {
run.compilation_run += other.compilation_run;
run.compilation_failure += other.compilation_failure;
run.test_run += other.test_run;
run.test_failure += other.test_failure;
}
};
fn compiler_run(allocator: Allocator, args: struct{
test_name: []const u8,
repetitions: usize,
extra_arguments: []const []const u8,
source_file_path: []const u8,
compiler_path: []const u8, compiler_path: []const u8,
}) !void { is_test: bool,
const test_names = try collectDirectoryDirEntries(allocator, args.directory_path); self_hosted: bool,
}) !Run {
std.debug.print("{s} [repetitions={}] {s}", .{args.test_name, args.repetitions, if (args.repetitions > 1) "\n\n" else ""});
var run = Run{};
const total_compilation_count = test_names.len; for (0..args.repetitions) |_| {
var ran_compilation_count: usize = 0; const base_argv: []const []const u8 = &.{ args.compiler_path, if (args.is_test) "test" else "exe", "-main_source_file", args.source_file_path };
var failed_compilation_count: usize = 0; const argv = try std.mem.concat(allocator, []const u8, &.{base_argv, args.extra_arguments});
var ran_test_count: usize = 0;
var failed_test_count: usize = 0;
const total_test_count = test_names.len;
std.debug.print("\n[{s} START]\n\n", .{args.group_name});
for (test_names) |test_name| {
std.debug.print("{s}... ", .{test_name});
const source_file_path = try std.mem.concat(allocator, u8, &.{ args.directory_path, "/", test_name, "/main.nat" });
const argv: []const []const u8 = &.{ args.compiler_path, if (args.is_test) "test" else "exe", "-main_source_file", source_file_path };
// if (std.mem.eql(u8, args.compiler_path, "nat/compiler_lightly_optimize_for_speed")) @breakpoint(); // if (std.mem.eql(u8, args.compiler_path, "nat/compiler_lightly_optimize_for_speed")) @breakpoint();
const compile_run = try std.ChildProcess.run(.{ const compile_run = try std.process.Child.run(.{
.allocator = allocator, .allocator = allocator,
// TODO: delete -main_source_file? // TODO: delete -main_source_file?
.argv = argv, .argv = argv,
.max_output_bytes = std.math.maxInt(u64), .max_output_bytes = std.math.maxInt(u64),
}); });
ran_compilation_count += 1; run.compilation_run += 1;
const compilation_result: TestError!bool = switch (compile_run.term) { const compilation_result: TestError!bool = switch (compile_run.term) {
.Exited => |exit_code| if (exit_code == 0) true else error.abnormal_exit_code, .Exited => |exit_code| if (exit_code == 0) true else error.abnormal_exit_code,
@ -71,7 +77,7 @@ fn runStandalone(allocator: Allocator, args: struct {
}; };
const compilation_success = compilation_result catch b: { const compilation_success = compilation_result catch b: {
failed_compilation_count += 1; run.compilation_failure += 1;
break :b false; break :b false;
}; };
@ -84,13 +90,13 @@ fn runStandalone(allocator: Allocator, args: struct {
} }
if (compilation_success and !args.self_hosted) { if (compilation_success and !args.self_hosted) {
const test_path = try std.mem.concat(allocator, u8, &.{ "nat/", test_name }); const test_path = try std.mem.concat(allocator, u8, &.{ "nat/", args.test_name });
const test_run = try std.ChildProcess.run(.{ const test_run = try std.process.Child.run(.{
.allocator = allocator, .allocator = allocator,
.argv = &.{test_path}, .argv = &.{test_path},
.max_output_bytes = std.math.maxInt(u64), .max_output_bytes = std.math.maxInt(u64),
}); });
ran_test_count += 1; run.test_run += 1;
const test_result: TestError!bool = switch (test_run.term) { const test_result: TestError!bool = switch (test_run.term) {
.Exited => |exit_code| if (exit_code == 0) true else error.abnormal_exit_code, .Exited => |exit_code| if (exit_code == 0) true else error.abnormal_exit_code,
.Signal => error.signaled, .Signal => error.signaled,
@ -99,9 +105,10 @@ fn runStandalone(allocator: Allocator, args: struct {
}; };
const test_success = test_result catch b: { const test_success = test_result catch b: {
failed_test_count += 1;
break :b false; break :b false;
}; };
run.test_failure += @intFromBool(!test_success);
std.debug.print("[TEST {s}]\n", .{if (test_success) "\x1b[32mOK\x1b[0m" else "\x1b[31mFAILED\x1b[0m"}); std.debug.print("[TEST {s}]\n", .{if (test_success) "\x1b[32mOK\x1b[0m" else "\x1b[31mFAILED\x1b[0m"});
if (test_run.stdout.len > 0) { if (test_run.stdout.len > 0) {
std.debug.print("STDOUT:\n\n{s}\n\n", .{test_run.stdout}); std.debug.print("STDOUT:\n\n{s}\n\n", .{test_run.stdout});
@ -114,14 +121,55 @@ fn runStandalone(allocator: Allocator, args: struct {
} }
} }
std.debug.print("\n{s} COMPILATIONS: {}. FAILED: {}\n", .{ args.group_name, total_compilation_count, failed_compilation_count }); return run;
std.debug.print("{s} TESTS: {}. RAN: {}. FAILED: {}\n", .{ args.group_name, total_test_count, ran_test_count, failed_test_count }); }
if (failed_compilation_count > 0 or failed_test_count > 0) { fn group_start(group: []const u8, test_count: usize) void {
std.debug.print("\n[{s} START ({} tests queued)]\n\n", .{group, test_count});
}
fn group_end(group: []const u8, test_count: usize, run: Run) !void {
std.debug.print("\n{s} COMPILATIONS: {}. FAILED: {}\n", .{ group, test_count, run.compilation_failure });
std.debug.print("{s} TESTS: {}. RAN: {}. FAILED: {}\n", .{ group, test_count, run.test_run, run.test_failure });
std.debug.print("\n[{s} END]\n\n", .{group});
if (run.compilation_failure > 0 or run.test_failure > 0) {
return error.fail; return error.fail;
} }
} }
fn runStandalone(allocator: Allocator, args: struct {
directory_path: []const u8,
group_name: []const u8,
self_hosted: bool,
is_test: bool,
compiler_path: []const u8,
repetitions: usize,
}) !void {
const test_names = try collectDirectoryDirEntries(allocator, args.directory_path);
std.debug.assert(args.repetitions > 0);
var total_run = Run{};
group_start(args.group_name, test_names.len * args.repetitions);
for (test_names) |test_name| {
const source_file_path = try std.mem.concat(allocator, u8, &.{ args.directory_path, "/", test_name, "/main.nat" });
const run = try compiler_run(allocator, .{
.compiler_path = args.compiler_path,
.source_file_path = source_file_path,
.test_name = test_name,
.repetitions = args.repetitions,
.extra_arguments = &.{},
.is_test = args.is_test,
.self_hosted = args.self_hosted,
});
total_run.add(run);
}
try group_end(args.group_name, test_names.len * args.repetitions, total_run);
}
fn runBuildTests(allocator: Allocator, args: struct { fn runBuildTests(allocator: Allocator, args: struct {
self_hosted: bool, self_hosted: bool,
compiler_path: []const u8, compiler_path: []const u8,
@ -579,34 +627,67 @@ fn run_test_suite(allocator: Allocator, args: struct {
return errors; return errors;
} }
fn c_abi_tests(allocator: Allocator) !void {
const test_count = 1;
const group = "C ABI";
group_start(group, test_count);
const run = try compiler_run(allocator, .{
.test_name = "c_abi",
.repetitions = 1,
.extra_arguments = &.{
"-c_source_files_start",
"test/build/c-abi/c.c",
"-c_source_files_end",
},
.source_file_path = "retest/c_abi/main.nat",
.compiler_path = bootstrap_relative_path,
.is_test = false,
.self_hosted = false,
});
try group_end(group, test_count, run);
}
pub fn main() !void { pub fn main() !void {
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
const allocator = arena.allocator(); const allocator = arena.allocator();
var errors = run_test_suite(allocator, .{ try runStandalone(allocator, .{
.self_hosted = false, .is_test = false,
.compiler_path = bootstrap_relative_path, .compiler_path = bootstrap_relative_path,
.self_hosted = false,
.group_name = "STANDALONE",
.directory_path = "retest/standalone",
.repetitions = 1,
}); });
if (!errors) { try c_abi_tests(allocator);
inline for (@typeInfo(Optimization).Enum.fields) |opt| {
const optimization = @field(Optimization, opt.name);
if (compile_self_hosted(allocator, .{
.is_test = false,
.optimization = optimization,
})) |compiler_path| {
errors = errors or run_test_suite(allocator, .{
.self_hosted = true,
.compiler_path = compiler_path,
});
} else |err| {
err catch {};
errors = true;
}
}
}
if (errors) { // var errors = run_test_suite(allocator, .{
return error.fail; // .self_hosted = false,
} // .compiler_path = bootstrap_relative_path,
// });
//
// if (!errors) {
// inline for (@typeInfo(Optimization).Enum.fields) |opt| {
// const optimization = @field(Optimization, opt.name);
// if (compile_self_hosted(allocator, .{
// .is_test = false,
// .optimization = optimization,
// })) |compiler_path| {
// errors = errors or run_test_suite(allocator, .{
// .self_hosted = true,
// .compiler_path = compiler_path,
// });
// } else |err| {
// err catch {};
// errors = true;
// }
// }
// }
//
// if (errors) {
// return error.fail;
// }
} }

View File

@ -4,12 +4,17 @@ set -ex
# Install LLVM and system dependencies # Install LLVM and system dependencies
wget https://apt.llvm.org/llvm.sh wget https://apt.llvm.org/llvm.sh
chmod +x llvm.sh chmod +x llvm.sh
sudo ./llvm.sh 17 all MY_LLVM_VERSION=18
sudo apt install liblld-17-dev libclang-17-dev liblld-17 ninja-build cmake -y sudo ./llvm.sh $MY_LLVM_VERSION all
sudo apt install liblld-$MY_LLVM_VERSION-dev libclang-$MY_LLVM_VERSION-dev liblld-$MY_LLVM_VERSION ninja-build cmake -y
# Install Zig # Install Zig
source ci/download_zig.sh source ci/download_zig.sh
download_zig master x86_64-linux download_zig master x86_64-linux
# Build and test # Build and test
zig build test -Dthird_party_ci=true
zig build test -Dthird_party_ci=true -Doptimize=Debug
zig build test -Dthird_party_ci=true -Doptimize=ReleaseSafe
zig build test -Dthird_party_ci=true -Doptimize=ReleaseSmall
zig build test -Dthird_party_ci=true -Doptimize=ReleaseFast

View File

@ -3,11 +3,14 @@ set -ex
# Install LLVM and system dependencies # Install LLVM and system dependencies
brew update brew update
brew install llvm@17 ninja brew install llvm@18 ninja
# Install Zig # Install Zig
source ci/download_zig.sh source ci/download_zig.sh
download_zig master aarch64-macos download_zig master aarch64-macos
# Build and test # Build and test
zig build test -Dthird_party_ci=true zig build test -Dthird_party_ci=true -Doptimize=Debug
zig build test -Dthird_party_ci=true -Doptimize=ReleaseSafe
zig build test -Dthird_party_ci=true -Doptimize=ReleaseSmall
zig build test -Dthird_party_ci=true -Doptimize=ReleaseFast

View File

@ -1,4 +1,4 @@
fn[extern] exit(exit_code: s32) noreturn; fn align_forward(n: u64, alignment: u64) u64 {
fn my_exit(exit_code: s32) noreturn { const mask = alignment - 1;
exit(exit_code); return (value + mask) & ~mask;
} }

481
retest/c_abi/main.nat Normal file
View File

@ -0,0 +1,481 @@
struct Struct_u64_u64 {
a: u64,
b: u64,
}
struct BigStruct {
a: u64,
b: u64,
c: u64,
d: u64,
e: u8,
}
bitfield(u8) SmallPackedStruct {
a: u2,
b: u2,
c: u2,
d: u2,
}
struct SmallStructInts{
a: u8,
b: u8,
c: u8,
d: u8,
}
struct SplitStructInt {
a: u64,
b: u8,
c: u32,
}
struct MedStructInts {
x: s32,
y: s32,
z: s32,
}
struct Rect {
left: u32,
right: u32,
top: u32,
bottom: u32,
}
struct StructWithArray {
a: s32,
padding: [4]u8,
b: s64,
}
struct ByRef {
val: s32,
arr: [15]s32,
}
struct ByValOrigin {
x: u64,
y: u64,
z: u64,
}
struct ByValSize{
width: u64,
height: u64,
depth: u64,
}
struct ByVal {
origin: ByValOrigin,
size: ByValSize,
}
fn[cc(.c)] run_c_tests[extern]() void;
fn[cc(.c)] c_u8[extern](x: u8) void;
fn[cc(.c)] c_u16[extern](x: u16) void;
fn[cc(.c)] c_u32[extern](x: u32) void;
fn[cc(.c)] c_u64[extern](x: u64) void;
fn[cc(.c)] c_s8[extern](x: s8) void;
fn[cc(.c)] c_s16[extern](x: s16) void;
fn[cc(.c)] c_s32[extern](x: s32) void;
fn[cc(.c)] c_s64[extern](x: s64) void;
fn[cc(.c)] c_bool[extern](x: u8) void;
fn[cc(.c)] c_five_integers[extern](a: s32, b: s32, c: s32, d: s32, e: s32) void;
fn[cc(.c)] c_ret_struct_u64_u64[extern]() Struct_u64_u64;
fn[cc(.c)] c_struct_u64_u64_0 [extern] (a: Struct_u64_u64) void;
fn[cc(.c)] c_struct_u64_u64_1 [extern] (a: u64, b: Struct_u64_u64) void;
fn[cc(.c)] c_struct_u64_u64_2 [extern] (a: u64, b: u64, c: Struct_u64_u64) void;
fn[cc(.c)] c_struct_u64_u64_3 [extern] (a: u64, b: u64, c: u64, d: Struct_u64_u64) void;
fn[cc(.c)] c_struct_u64_u64_4 [extern] (a: u64, b: u64, c: u64, d: u64, e: Struct_u64_u64) void;
fn[cc(.c)] c_struct_u64_u64_5 [extern] (a: u64, b: u64, c: u64, d: u64, e: u64, f: Struct_u64_u64) void;
fn[cc(.c)] c_struct_u64_u64_6 [extern] (a: u64, b: u64, c: u64, d: u64, e: u64, f: u64, g: Struct_u64_u64) void;
fn[cc(.c)] c_struct_u64_u64_7 [extern] (a: u64, b: u64, c: u64, d: u64, e: u64, f: u64, g: u64, h: Struct_u64_u64) void;
fn[cc(.c)] c_struct_u64_u64_8 [extern] (a: u64, b: u64, c: u64, d: u64, e: u64, f: u64, g: u64, h: u64, i: Struct_u64_u64) void;
fn [cc(.c)] c_big_struct[extern](x: BigStruct) void;
fn [cc(.c)] c_small_struct_ints[extern](x: SmallStructInts) void;
fn [cc(.c)] c_ret_small_struct_ints[extern]() SmallStructInts;
fn [cc(.c)] c_med_struct_ints[extern](x: MedStructInts) void;
fn [cc(.c)] c_ret_med_struct_ints[extern]() MedStructInts;
fn [cc(.c)] c_small_packed_struct[extern](x: SmallPackedStruct) void;
fn [cc(.c)] c_ret_small_packed_struct[extern]() SmallPackedStruct;
fn [cc(.c)] c_split_struct_ints[extern](x: SplitStructInt) void;
fn [cc(.c)] c_big_struct_both[extern](x: BigStruct) BigStruct;
fn [cc(.c)] c_multiple_struct_ints[extern](a: Rect, b: Rect) void;
fn [cc(.c)] c_ret_bool[extern]() u8;
fn [cc(.c)] c_ret_u8[extern]() u8;
fn [cc(.c)] c_ret_u16[extern]() u16;
fn [cc(.c)] c_ret_u32[extern]() u32;
fn [cc(.c)] c_ret_u64[extern]() u64;
fn [cc(.c)] c_ret_s8[extern]() s8;
fn [cc(.c)] c_ret_s16[extern]() s16;
fn [cc(.c)] c_ret_s32[extern]() s32;
fn [cc(.c)] c_ret_s64[extern]() s64;
fn [cc(.c)] c_struct_with_array[extern](x: StructWithArray) void;
fn [cc(.c)] c_ret_struct_with_array[extern]() StructWithArray;
fn [cc(.c)] c_modify_by_ref_param[extern](x: ByRef) ByRef;
fn [cc(.c)] c_func_ptr_byval[extern] (a: u64, b: u64, c: ByVal, d: u64, e: u64, f: u64) void;
fn[cc(.c)] main[export]() s32
{
run_c_tests();
c_u8(0xff);
c_u16(0xfffe);
c_u32(0xfffffffd);
c_u64(0xfffffffffffffffc);
//if (has_i128) {
// c_struct_u128({ .value = 0xfffffffffffffffc, });
//}
c_s8(-1);
c_s16(-2);
c_s32(-3);
c_s64(-4);
//if (has_i128) {
// c_struct_i128({ .value = -6, });
//}
c_bool(1);
c_five_integers(12, 34, 56, 78, 90);
>s = c_ret_struct_u64_u64();
#require(s.a == 21);
#require(s.b == 22);
c_struct_u64_u64_0({ .a = 23, .b = 24, });
c_struct_u64_u64_1(0, { .a = 25, .b = 26, });
c_struct_u64_u64_2(0, 1, { .a = 27, .b = 28, });
c_struct_u64_u64_3(0, 1, 2, { .a = 29, .b = 30, });
c_struct_u64_u64_4(0, 1, 2, 3, { .a = 31, .b = 32, });
c_struct_u64_u64_5(0, 1, 2, 3, 4, { .a = 33, .b = 34, });
c_struct_u64_u64_6(0, 1, 2, 3, 4, 5, { .a = 35, .b = 36, });
c_struct_u64_u64_7(0, 1, 2, 3, 4, 5, 6, { .a = 37, .b = 38, });
c_struct_u64_u64_8(0, 1, 2, 3, 4, 5, 6, 7, { .a = 39, .b = 40, });
>big_struct: BigStruct = {
.a = 1,
.b = 2,
.c = 3,
.d = 4,
.e = 5,
};
c_big_struct(big_struct);
>small: SmallStructInts = {
.a = 1,
.b = 2,
.c = 3,
.d = 4,
};
c_small_struct_ints(small);
>small2 = c_ret_small_struct_ints();
#require(small2.a == 1);
#require(small2.b == 2);
#require(small2.c == 3);
#require(small2.d == 4);
>med: MedStructInts = {
.x = 1,
.y = 2,
.z = 3,
};
c_med_struct_ints(med);
>med2 = c_ret_med_struct_ints();
#require(med2.x == 1);
#require(med2.y == 2);
#require(med2.z == 3);
>p: SmallPackedStruct = { .a = 0, .b = 1, .c = 2, .d = 3, };
c_small_packed_struct(p);
>p2 = c_ret_small_packed_struct();
#require(p2.a == 0);
#require(p2.b == 1);
#require(p2.c == 2);
#require(p2.d == 3);
>split: SplitStructInt = {
.a = 1234,
.b = 100,
.c = 1337,
};
c_split_struct_ints(split);
> big: BigStruct = {
.a = 1,
.b = 2,
.c = 3,
.d = 4,
.e = 5,
};
>big2 = c_big_struct_both(big);
#require(big2.a == 10);
#require(big2.b == 11);
#require(big2.c == 12);
#require(big2.d == 13);
#require(big2.e == 14);
>r1: Rect = {
.left = 1,
.right = 21,
.top = 16,
.bottom = 4,
};
>r2: Rect = {
.left = 178,
.right = 189,
.top = 21,
.bottom = 15,
};
c_multiple_struct_ints(r1, r2);
#require(c_ret_bool() == 1);
#require(c_ret_u8() == 0xff);
#require(c_ret_u16() == 0xffff);
#require(c_ret_u32() == 0xffffffff);
#require(c_ret_u64() == 0xffffffffffffffff);
#require(c_ret_s8() == -1);
#require(c_ret_s16() == -1);
#require(c_ret_s32() == -1);
#require(c_ret_s64() == -1);
c_struct_with_array({ .a = 1, .padding = undefined, .b = 2, });
>x = c_ret_struct_with_array();
#require(x.a == 4);
#require(x.b == 155);
>res = c_modify_by_ref_param({ .val = 1, .arr = undefined, });
#require(res.val == 42);
>function_pointer = c_func_ptr_byval&;
function_pointer(1, 2, { .origin = { .x = 9, .y = 10, .z = 11, }, .size = { .width = 12, .height = 13, .depth = 14, }, }, 3, 4, 5);
return 0;
}
fn[cc(.c)] nat_u8[export] (x: u8) void {
#require(x == 0xff);
}
fn[cc(.c)] nat_u16 [export] (x: u16) void {
#require(x == 0xfffe);
}
fn[cc(.c)] nat_u32 [export] (x: u32) void {
#require(x == 0xfffffffd);
}
fn[cc(.c)] nat_u64 [export] (x: u64) void {
#require(x == 0xfffffffffffffffc);
}
fn[cc(.c)] nat_s8 [export] (x: s8) void {
#require(x == -1);
}
fn[cc(.c)] nat_s16 [export] (x: s16) void {
#require(x == -2);
}
fn[cc(.c)] nat_s32 [export] (x: s32) void {
#require(x == -3);
}
fn[cc(.c)] nat_s64 [export] (x: s64) void {
#require(x == -4);
}
fn[cc(.c)] nat_ptr [export] (x: *u8) void {
#require(#int_from_pointer(x) == 0xdeadbeef);
}
fn[cc(.c)] nat_five_integers [export] (a: s32, b: s32, c: s32, d: s32, e: s32) void {
#require(a == 12);
#require(b == 34);
#require(c == 56);
#require(d == 78);
#require(e == 90);
}
fn[cc(.c)] nat_bool [export] (x: u8) void {
#require(x);
}
fn[cc(.c)] nat_ret_struct_u64_u64 [export] () Struct_u64_u64 {
return { .a = 1, .b = 2, };
}
fn[cc(.c)] nat_struct_u64_u64_0 [export] (s: Struct_u64_u64) void {
#require(s.a == 3);
#require(s.b == 4);
}
fn[cc(.c)] nat_struct_u64_u64_1 [export] (_: u64, s: Struct_u64_u64) void {
#require(s.a == 5);
#require(s.b == 6);
}
fn[cc(.c)] nat_struct_u64_u64_2 [export] (_: u64, _: u64, s: Struct_u64_u64) void {
#require(s.a == 7);
#require(s.b == 8);
}
fn[cc(.c)] nat_struct_u64_u64_3 [export] (_: u64, _: u64, _: u64, s: Struct_u64_u64) void {
#require(s.a == 9);
#require(s.b == 10);
}
fn[cc(.c)] nat_struct_u64_u64_4 [export](_: u64, _: u64, _: u64, _: u64, s: Struct_u64_u64) void {
#require(s.a == 11);
#require(s.b == 12);
}
fn[cc(.c)] nat_struct_u64_u64_5 [export](_: u64, _: u64, _: u64, _: u64, _: u64, s: Struct_u64_u64) void {
#require(s.a == 13);
#require(s.b == 14);
}
fn[cc(.c)] nat_struct_u64_u64_6 [export](_: u64, _: u64, _: u64, _: u64, _: u64, _: u64, s: Struct_u64_u64) void {
#require(s.a == 15);
#require(s.b == 16);
}
fn[cc(.c)] nat_struct_u64_u64_7 [export](_: u64, _: u64, _: u64, _: u64, _: u64, _: u64, _: u64, s: Struct_u64_u64) void {
#require(s.a == 17);
#require(s.b == 18);
}
fn[cc(.c)] nat_struct_u64_u64_8 [export](_: u64, _: u64, _: u64, _: u64, _: u64, _: u64, _: u64, _: u64, s: Struct_u64_u64) void {
#require(s.a == 19);
#require(s.b == 20);
}
fn[cc(.c)] nat_big_struct [export] (x: BigStruct) void {
#require(x.a == 1);
#require(x.b == 2);
#require(x.c == 3);
#require(x.d == 4);
#require(x.e == 5);
}
fn[cc(.c)] nat_small_packed_struct [export] (x: SmallPackedStruct) void {
#require(x.a == 0);
#require(x.b == 1);
#require(x.c == 2);
#require(x.d == 3);
}
fn[cc(.c)] nat_split_struct_ints [export] (x: SplitStructInt) void {
#require(x.a == 1234);
#require(x.b == 100);
#require(x.c == 1337);
}
fn[cc(.c)] nat_big_struct_both [export] (x: BigStruct) BigStruct {
#require(x.a == 30);
#require(x.b == 31);
#require(x.c == 32);
#require(x.d == 33);
#require(x.e == 34);
>s: BigStruct = {
.a = 20,
.b = 21,
.c = 22,
.d = 23,
.e = 24,
};
return s;
}
fn[cc(.c)] nat_ret_bool[export] () u8 {
return 1;
}
fn[cc(.c)] nat_ret_u8[export] () u8 {
return 0xff;
}
fn[cc(.c)] nat_ret_u16[export] () u16 {
return 0xffff;
}
fn[cc(.c)] nat_ret_u32[export] () u32 {
return 0xffffffff;
}
fn[cc(.c)] nat_ret_u64[export] () u64 {
return 0xffffffffffffffff;
}
fn[cc(.c)] nat_ret_s8[export] () s8 {
return -1;
}
fn[cc(.c)] nat_ret_s16[export] () s16 {
return -1;
}
fn[cc(.c)] nat_ret_s32[export] () s32 {
return -1;
}
fn[cc(.c)] nat_ret_s64[export] () s64 {
return -1;
}
fn[cc(.c)] nat_ret_small_struct_ints[export] () SmallStructInts {
return {
.a = 1,
.b = 2,
.c = 3,
.d = 4,
};
}
fn[cc(.c)] nat_ret_med_struct_ints[export] () MedStructInts {
return {
.x = 1,
.y = 2,
.z = 3,
};
}
fn[cc(.c)] nat_multiple_struct_ints [export] (x: Rect, y: Rect) void {
#require(x.left == 1);
#require(x.right == 21);
#require(x.top == 16);
#require(x.bottom == 4);
#require(y.left == 178);
#require(y.right == 189);
#require(y.top == 21);
#require(y.bottom == 15);
}
fn [cc(.c)] nat_small_struct_ints [export] (x: SmallStructInts) void {
#require(x.a == 1);
#require(x.b == 2);
#require(x.c == 3);
#require(x.d == 4);
}
fn [cc(.c)] nat_med_struct_ints [export] (s: MedStructInts) void {
#require(s.x == 1);
#require(s.y == 2);
#require(s.z == 3);
}

View File

@ -0,0 +1,8 @@
fn [cc(.c)] main [export]() s32 {
>a: s32 = 1;
>b: s32 = 2;
>c = a + b;
>d: s32 = 3;
>e = d - c;
return e;
}

View File

@ -0,0 +1,7 @@
fn [cc(.c)] main [export]() s32
{
>a: s32 = 5;
>b: s32 = 4;
>result = a & b;
return result - b;
}

View File

@ -0,0 +1,4 @@
fn[cc(.c)] main[export]() s32 {
>array: [1]s32 = [0];
return array[0];
}

View File

@ -0,0 +1,5 @@
fn[cc(.c)] main[export]() s32 {
>n: s32 = 1;
#assert(n);
return n - n;
}

View File

@ -0,0 +1,25 @@
bitfield(s32) Bitfield{
a: u1,
b: u1,
c: u1,
d: u29,
}
fn[cc(.c)] main[export]() s32 {
>bf: Bitfield = {
.a = 0,
.b = 1,
.c = 1,
.d = 0,
};
>bf_int: s32 = #transmute(bf);
>bf_int2: s32 = 6;
>bf2: Bitfield = #transmute(bf_int2);
#assert(bf.a == bf2.a);
#assert(bf.b == bf2.b);
#assert(bf.c == bf2.c);
#assert(bf.d == bf2.d);
return bf_int - bf_int2;
}

View File

@ -0,0 +1,7 @@
import "file.nat";
fn [cc(.c)] main [export]() s32
{
>result: s32 = file.foo();
return result;
}

View File

@ -0,0 +1,9 @@
// comment
fn[cc(.c)]
// comment
main[export]()
// comment
s32 { // comment
// comment
return 0; // comment
} // comment

View File

@ -0,0 +1,16 @@
fn foo() s32 {
return 5;
}
fn[cc(.c)] main[export] () s32 {
>a = foo();
if (a > 4) {
a += 2;
} else {
a += 1;
}
a += 1;
return a - 8;
}

View File

@ -0,0 +1,5 @@
fn [cc(.c)] main [export]() s32
{
>result: s32 = 0;
return result;
}

View File

@ -0,0 +1,7 @@
fn [cc(.c)] main [export] () s32 {
>dividend: s32 = 30;
>divisor: s32 = 6;
>result = dividend / divisor;
>n: s32 = 5;
return n - result;
}

View File

@ -0,0 +1,10 @@
fn [cc(.c)] main [export] () s32 {
>result: s32 = 0;
if (result > 0) {
return 1;
} else if (result == 0) {
return 0;
} else {
return 1;
}
}

View File

@ -0,0 +1,3 @@
fn [cc(.c)] main [export] (argc: s32) s32 {
return argc - argc;
}

View File

@ -0,0 +1,10 @@
>n: s32 = 5;
fn foo() s32 {
return n;
}
fn[cc(.c)] main[export]() s32 {
>fn_pointer = foo&;
>a = fn_pointer();
return a - n;
}

View File

@ -0,0 +1,5 @@
>n: s32 = 1;
fn[cc(.c)] main[export]() s32 {
n = 0;
return n;
}

View File

@ -0,0 +1,6 @@
fn [cc(.c)] write[extern](file_descriptor: s32, byte_pointer: *u8, byte_count: u64) s64;
fn [cc(.c)] main[export]() s32 {
>arr: [4]u8 = ['H', 'i', '!', '\n'];
write(1, arr&, arr.length);
return 0;
}

View File

@ -0,0 +1,9 @@
fn [cc(.c)] write[extern](file_descriptor: s32, byte_pointer: *u8, byte_count: u64) s64;
fn[cc(.c)] main[export]() s32 {
>local_string = "Hello world from local string!\n";
write(1, local_string&, local_string.length);
>global_string: []u8 = "Hello world from global string!\n";
write(1, global_string.pointer, global_string.length);
return 0;
}

View File

@ -0,0 +1,11 @@
fn foo() s32 {
return 1;
}
fn [cc(.c)] main [export] () s32 {
>a = foo();
if (a == 1) {
return 0;
} else {
return 1;
}
}

View File

@ -0,0 +1,7 @@
fn[cc(.c)] main[export]() s32 {
>a: s32 = 0xffffffff;
#assert(#leading_zeroes(a) == 0);
>b: s32 = 0x1fffffff;
#assert(#leading_zeroes(b) == 3);
return 0;
}

View File

@ -0,0 +1,9 @@
fn[cc(.c)] main[export]() s32 {
>i: s32 = 0;
>top: s32 = 10;
loop (i < top) {
i += 1;
}
return i - top;
}

View File

@ -0,0 +1,12 @@
fn[cc(.c)] main[export]() s32 {
>i: s32 = 0;
>n: s32 = 5;
loop (i < 10) {
i += 1;
if (i == n) {
break;
}
}
return i - n;
}

View File

@ -0,0 +1,13 @@
fn[cc(.c)] main[export]() s32 {
>i: s32 = 0;
>n: s32 = 0;
loop (i < 10) {
i += 1;
if (n == 0) {
continue;
}
n += 1;
}
return n;
}

View File

@ -0,0 +1,18 @@
fn foo() s32 {
>n: s32 = 6;
>a: s32 = 0;
loop {
if (a == n) {
return a;
}
a += 1;
}
}
fn[cc(.c)] main[export]() s32 {
>n: s32 = 6;
>result = foo();
return result - n;
}

View File

@ -0,0 +1,21 @@
>n: s32 = 10;
>m: s32 = 3;
fn foo(arg: s32) s32 {
>i: s32 = 0;
loop (i < arg) {
if (i < m) {
i += 1;
} else {
return i - 100;
}
}
return 321;
}
fn[cc(.c)] main[export]() s32 {
>a = foo(n);
>b = foo(n);
return (a - b) + (a + 97) + (b + 97);
}

View File

@ -0,0 +1,21 @@
>m: s32 = 2;
>n: s32 = 6;
fn foo(arg: s32) s32 {
>i: s32 = 0;
loop (i < arg) {
if (i > 2) {
return i;
}
i += 1;
}
return 15;
}
fn[cc(.c)] main[export]() s32 {
>a = foo(n);
>b = foo(n);
return (a - b) + (a - (m + 1)) + (b - (m + 1));
}

View File

@ -0,0 +1,7 @@
fn[cc(.c)] main[export]() s32 {
>i: s32 = 0;
loop (i < 1) {
return 0;
}
return 1;
}

View File

@ -0,0 +1,19 @@
fn foo(arg: s32) s32 {
if (arg > 1) {
return 6;
} else {
return 0;
}
}
fn[cc(.c)] main[export]() s32 {
>a = foo(5);
>b = foo(5);
if (a - 6 != 0) {
return 1;
}
if (b - 6 != 0) {
return 1;
}
return a - b;
}

View File

@ -0,0 +1,5 @@
fn [cc(.c)] main [export] () s32 {
>a: s32 = 5;
>b: s32 = 4;
return (a * b) - (a * b);
}

View File

@ -0,0 +1,18 @@
fn foo (arg: s32) s32 {
if (arg > 1) {
if (arg < 5) {
return 6;
} else {
return 5;
}
} else {
return 0;
}
}
fn[cc(.c)] main[export] () s32 {
>a = foo(5);
>b = foo(5);
return a - b;
}

View File

@ -0,0 +1,14 @@
fn align_forward(value: s32, alignment: s32) s32 {
>mask = alignment - 1;
return (value + mask) & ~mask;
}
fn [cc(.c)] main [export] () s32 {
>a: s32 = 1;
>aligned_a = align_forward(a, 8);
>b: s32 = 9;
>aligned_b = align_forward(b, 8);
>c: s32 = 512;
>aligned_c = align_forward(c, 0x1000);
return (aligned_a - 8) + (aligned_b - 16) + (aligned_c - 0x1000);
}

View File

@ -0,0 +1,7 @@
fn [cc(.c)] main [export] () s32 {
>a: s32 = 0xffff;
>b: s32 = 0xffff0000;
>c: s32 = 0xffffffff;
>result = c - (a | b);
return result;
}

View File

@ -0,0 +1,9 @@
fn[cc(.c)] main[export]() s32 {
>a: s32 = 5;
>b: s32 = a orelse 4;
#assert(b == a);
>c: s32 = 0;
>d: s32 = c orelse a;
#assert(d == a);
return 0;
}

View File

@ -0,0 +1,7 @@
fn[cc(.c)] main[export]() s32 {
return foo();
}
fn foo() s32 {
return 0;
}

View File

@ -0,0 +1,10 @@
struct SimplePolymorphic[$T] {
member: T,
}
fn[cc(.c)] main[export]() s32 {
>s: SimplePolymorphic[s32] = {
.member = 0,
};
return s.member;
}

View File

@ -0,0 +1,6 @@
fn[cc(.c)] main[export]() s32 {
>a: s32 = 0;
>pointer = a&;
pointer@ = 4;
return pointer@ - a;
}

View File

@ -0,0 +1,6 @@
fn [cc(.c)] main [export] () s32 {
>a: s32 = 1;
>b: s32 = a << 5;
>c: s32 = b >> 5;
return c - a;
}

View File

@ -0,0 +1,12 @@
fn[cc(.c)] main[export]() s32 {
>constant: s32 = 4;
>result: s32 = 0;
if (result > 0) {
result = constant - 1;
} else {
result = constant;
}
return result - constant;
}

View File

@ -0,0 +1,6 @@
fn[cc(.c)] main[export]() s32 {
>sizeofu32: s32 = #size(u32);
>sizeofu16: s32 = #size(u16);
return sizeofu32 - (2 * sizeofu16);
}

View File

@ -0,0 +1,10 @@
struct Struct {
a: s32,
}
fn[cc(.c)] main[export]() s32 {
>result: Struct = {
.a = 0,
};
return result.a;
}

View File

@ -0,0 +1,7 @@
fn[cc(.c)] main[export]() s32 {
>a: s32 = 7;
#assert(#trailing_zeroes(a) == 0);
>b: s32 = 8;
#assert(#trailing_zeroes(b) == 3);
return 0;
}

View File

@ -0,0 +1,7 @@
fn [cc(.c)] main [export] () s32 {
>a: s32 = 561;
>b: s32 = 124;
>c = a ^ b;
>d = a ^ b;
return c ^ d;
}

14
script.sh Normal file
View File

@ -0,0 +1,14 @@
#!/bin/bash
set -ex
MY_SOURCE_FILE=retest/standalone/call_other_file/main.nat
i=$((0))
while ((i < 1000)); do
zig build run -Dprint_stack_trace=true -Doptimize=Debug -- exe -main_source_file $MY_SOURCE_FILE
zig build run -Dprint_stack_trace=true -Doptimize=ReleaseSafe -- exe -main_source_file $MY_SOURCE_FILE
zig build run -Dprint_stack_trace=true -Doptimize=ReleaseSmall -- exe -main_source_file $MY_SOURCE_FILE
zig build run -Dprint_stack_trace=true -Doptimize=ReleaseFast -- exe -main_source_file $MY_SOURCE_FILE
i=$((i + 1))
done

View File

@ -28,6 +28,7 @@
#include "llvm/ADT/Statistic.h" #include "llvm/ADT/Statistic.h"
#include "llvm/Config/llvm-config.h" #include "llvm/Config/llvm-config.h"
#include "llvm/LinkAllPasses.h" #include "llvm/LinkAllPasses.h"
#include "llvm/MC/MCSubtargetInfo.h"
#include "llvm/MC/TargetRegistry.h" #include "llvm/MC/TargetRegistry.h"
#include "llvm/Option/Arg.h" #include "llvm/Option/Arg.h"
#include "llvm/Option/ArgList.h" #include "llvm/Option/ArgList.h"
@ -38,12 +39,15 @@
#include "llvm/Support/ManagedStatic.h" #include "llvm/Support/ManagedStatic.h"
#include "llvm/Support/Path.h" #include "llvm/Support/Path.h"
#include "llvm/Support/Process.h" #include "llvm/Support/Process.h"
#include "llvm/Support/RISCVISAInfo.h"
#include "llvm/Support/Signals.h" #include "llvm/Support/Signals.h"
#include "llvm/Support/TargetSelect.h" #include "llvm/Support/TargetSelect.h"
#include "llvm/Support/TimeProfiler.h" #include "llvm/Support/TimeProfiler.h"
#include "llvm/Support/Timer.h" #include "llvm/Support/Timer.h"
#include "llvm/Support/raw_ostream.h" #include "llvm/Support/raw_ostream.h"
#include "llvm/Target/TargetMachine.h" #include "llvm/Target/TargetMachine.h"
#include "llvm/TargetParser/AArch64TargetParser.h"
#include "llvm/TargetParser/ARMTargetParser.h"
#include <cstdio> #include <cstdio>
#ifdef CLANG_HAVE_RLIMITS #ifdef CLANG_HAVE_RLIMITS
@ -182,6 +186,43 @@ static int PrintSupportedCPUs(std::string TargetStr) {
return 0; return 0;
} }
static int PrintSupportedExtensions(std::string TargetStr) {
std::string Error;
const llvm::Target *TheTarget =
llvm::TargetRegistry::lookupTarget(TargetStr, Error);
if (!TheTarget) {
llvm::errs() << Error;
return 1;
}
llvm::TargetOptions Options;
std::unique_ptr<llvm::TargetMachine> TheTargetMachine(
TheTarget->createTargetMachine(TargetStr, "", "", Options, std::nullopt));
const llvm::Triple &MachineTriple = TheTargetMachine->getTargetTriple();
const llvm::MCSubtargetInfo *MCInfo = TheTargetMachine->getMCSubtargetInfo();
const llvm::ArrayRef<llvm::SubtargetFeatureKV> Features =
MCInfo->getAllProcessorFeatures();
llvm::StringMap<llvm::StringRef> DescMap;
for (const llvm::SubtargetFeatureKV &feature : Features)
DescMap.insert({feature.Key, feature.Desc});
if (MachineTriple.isRISCV())
llvm::riscvExtensionsHelp(DescMap);
else if (MachineTriple.isAArch64())
llvm::AArch64::PrintSupportedExtensions(DescMap);
else if (MachineTriple.isARM())
llvm::ARM::PrintSupportedExtensions(DescMap);
else {
// The option was already checked in Driver::HandleImmediateArgs,
// so we do not expect to get here if we are not a supported architecture.
assert(0 && "Unhandled triple for --print-supported-extensions option.");
return 1;
}
return 0;
}
int cc1_main(ArrayRef<const char *> Argv, const char *Argv0, void *MainAddr) { int cc1_main(ArrayRef<const char *> Argv, const char *Argv0, void *MainAddr) {
ensureSufficientStack(); ensureSufficientStack();
@ -221,6 +262,10 @@ int cc1_main(ArrayRef<const char *> Argv, const char *Argv0, void *MainAddr) {
if (Clang->getFrontendOpts().PrintSupportedCPUs) if (Clang->getFrontendOpts().PrintSupportedCPUs)
return PrintSupportedCPUs(Clang->getTargetOpts().Triple); return PrintSupportedCPUs(Clang->getTargetOpts().Triple);
// --print-supported-extensions takes priority over the actual compilation.
if (Clang->getFrontendOpts().PrintSupportedExtensions)
return PrintSupportedExtensions(Clang->getTargetOpts().Triple);
// Infer the builtin include path if unspecified. // Infer the builtin include path if unspecified.
if (Clang->getHeaderSearchOpts().UseBuiltinIncludes && if (Clang->getHeaderSearchOpts().UseBuiltinIncludes &&
Clang->getHeaderSearchOpts().ResourceDir.empty()) Clang->getHeaderSearchOpts().ResourceDir.empty())

View File

@ -204,10 +204,10 @@ bool AssemblerInvocation::CreateFromArgs(AssemblerInvocation &Opts,
// Parse the arguments. // Parse the arguments.
const OptTable &OptTbl = getDriverOptTable(); const OptTable &OptTbl = getDriverOptTable();
const unsigned IncludedFlagsBitmask = options::CC1AsOption; llvm::opt::Visibility VisibilityMask(options::CC1AsOption);
unsigned MissingArgIndex, MissingArgCount; unsigned MissingArgIndex, MissingArgCount;
InputArgList Args = OptTbl.ParseArgs(Argv, MissingArgIndex, MissingArgCount, InputArgList Args =
IncludedFlagsBitmask); OptTbl.ParseArgs(Argv, MissingArgIndex, MissingArgCount, VisibilityMask);
// Check for missing argument error. // Check for missing argument error.
if (MissingArgCount) { if (MissingArgCount) {
@ -220,7 +220,7 @@ bool AssemblerInvocation::CreateFromArgs(AssemblerInvocation &Opts,
for (const Arg *A : Args.filtered(OPT_UNKNOWN)) { for (const Arg *A : Args.filtered(OPT_UNKNOWN)) {
auto ArgString = A->getAsString(Args); auto ArgString = A->getAsString(Args);
std::string Nearest; std::string Nearest;
if (OptTbl.findNearest(ArgString, Nearest, IncludedFlagsBitmask) > 1) if (OptTbl.findNearest(ArgString, Nearest, VisibilityMask) > 1)
Diags.Report(diag::err_drv_unknown_argument) << ArgString; Diags.Report(diag::err_drv_unknown_argument) << ArgString;
else else
Diags.Report(diag::err_drv_unknown_argument_with_suggestion) Diags.Report(diag::err_drv_unknown_argument_with_suggestion)
@ -643,9 +643,10 @@ int cc1as_main(ArrayRef<const char *> Argv, const char *Argv0, void *MainAddr) {
if (Asm.ShowHelp) { if (Asm.ShowHelp) {
getDriverOptTable().printHelp( getDriverOptTable().printHelp(
llvm::outs(), "clang -cc1as [options] file...", llvm::outs(), "clang -cc1as [options] file...",
"Clang Integrated Assembler", "Clang Integrated Assembler", /*ShowHidden=*/false,
/*Include=*/driver::options::CC1AsOption, /*Exclude=*/0, /*ShowAllAliases=*/false,
/*ShowAllAliases=*/false); llvm::opt::Visibility(driver::options::CC1AsOption));
return 0; return 0;
} }

View File

@ -36,7 +36,6 @@
#include "llvm/Support/CrashRecoveryContext.h" #include "llvm/Support/CrashRecoveryContext.h"
#include "llvm/Support/ErrorHandling.h" #include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/FileSystem.h" #include "llvm/Support/FileSystem.h"
#include "llvm/Support/InitLLVM.h"
#include "llvm/Support/LLVMDriver.h" #include "llvm/Support/LLVMDriver.h"
#include "llvm/Support/Path.h" #include "llvm/Support/Path.h"
#include "llvm/Support/PrettyStackTrace.h" #include "llvm/Support/PrettyStackTrace.h"
@ -65,7 +64,7 @@ std::string GetExecutablePath(const char *Argv0, bool CanonicalPrefixes) {
if (llvm::ErrorOr<std::string> P = if (llvm::ErrorOr<std::string> P =
llvm::sys::findProgramByName(ExecutablePath)) llvm::sys::findProgramByName(ExecutablePath))
ExecutablePath = *P; ExecutablePath = *P;
return std::string(ExecutablePath.str()); return std::string(ExecutablePath);
} }
// This just needs to be some symbol in the binary; C++ doesn't // This just needs to be some symbol in the binary; C++ doesn't
@ -79,9 +78,9 @@ static const char *GetStableCStr(std::set<std::string> &SavedStrings,
return SavedStrings.insert(std::string(S)).first->c_str(); return SavedStrings.insert(std::string(S)).first->c_str();
} }
/// ApplyQAOverride - Apply a list of edits to the input argument lists. /// ApplyOneQAOverride - Apply a list of edits to the input argument lists.
/// ///
/// The input string is a space separate list of edits to perform, /// The input string is a space separated list of edits to perform,
/// they are applied in order to the input argument lists. Edits /// they are applied in order to the input argument lists. Edits
/// should be one of the following forms: /// should be one of the following forms:
/// ///
@ -122,7 +121,7 @@ static void ApplyOneQAOverride(raw_ostream &OS,
GetStableCStr(SavedStrings, Edit.substr(1)); GetStableCStr(SavedStrings, Edit.substr(1));
OS << "### Adding argument " << Str << " at end\n"; OS << "### Adding argument " << Str << " at end\n";
Args.push_back(Str); Args.push_back(Str);
} else if (Edit[0] == 's' && Edit[1] == '/' && Edit.endswith("/") && } else if (Edit[0] == 's' && Edit[1] == '/' && Edit.ends_with("/") &&
Edit.slice(2, Edit.size() - 1).contains('/')) { Edit.slice(2, Edit.size() - 1).contains('/')) {
StringRef MatchPattern = Edit.substr(2).split('/').first; StringRef MatchPattern = Edit.substr(2).split('/').first;
StringRef ReplPattern = Edit.substr(2).split('/').second; StringRef ReplPattern = Edit.substr(2).split('/').second;
@ -177,7 +176,7 @@ static void ApplyOneQAOverride(raw_ostream &OS,
} }
} }
/// ApplyQAOverride - Apply a comma separate list of edits to the /// ApplyQAOverride - Apply a space separated list of edits to the
/// input argument lists. See ApplyOneQAOverride. /// input argument lists. See ApplyOneQAOverride.
static void ApplyQAOverride(SmallVectorImpl<const char*> &Args, static void ApplyQAOverride(SmallVectorImpl<const char*> &Args,
const char *OverrideStr, const char *OverrideStr,
@ -371,14 +370,6 @@ static int ExecuteCC1Tool(SmallVectorImpl<const char *> &ArgV,
static int clang_main(int Argc, char **Argv, const llvm::ToolContext &ToolContext) { static int clang_main(int Argc, char **Argv, const llvm::ToolContext &ToolContext) {
noteBottomOfStack(); noteBottomOfStack();
// ZIG PATCH: On Windows, InitLLVM calls GetCommandLineW(),
// and overwrites the args. We don't want it to do that,
// and we also don't need the signal handlers it installs
// (we have our own already), so we just use llvm_shutdown_obj
// instead.
// llvm::InitLLVM X(Argc, Argv);
llvm::llvm_shutdown_obj X;
llvm::setBugReportMsg("PLEASE submit a bug report to " BUG_REPORT_URL llvm::setBugReportMsg("PLEASE submit a bug report to " BUG_REPORT_URL
" and include the crash backtrace, preprocessed " " and include the crash backtrace, preprocessed "
"source, and associated run script.\n"); "source, and associated run script.\n");
@ -405,7 +396,7 @@ static int clang_main(int Argc, char **Argv, const llvm::ToolContext &ToolContex
} }
// Handle -cc1 integrated tools. // Handle -cc1 integrated tools.
if (Args.size() >= 2 && StringRef(Args[1]).startswith("-cc1")) if (Args.size() >= 2 && StringRef(Args[1]).starts_with("-cc1"))
return ExecuteCC1Tool(Args, ToolContext); return ExecuteCC1Tool(Args, ToolContext);
// Handle options that need handling before the real command line parsing in // Handle options that need handling before the real command line parsing in
@ -606,6 +597,6 @@ static int clang_main(int Argc, char **Argv, const llvm::ToolContext &ToolContex
return Res; return Res;
} }
extern "C" int NativityClangMain(int argc, char **argv) { extern "C" int nat_clang_main(int argc, char ** argv) {
return clang_main(argc, argv, {argv[0], nullptr, false}); return clang_main(argc, argv, {argv[0], nullptr, false});
} }

View File

@ -4,7 +4,6 @@
#include "llvm/IR/Module.h" #include "llvm/IR/Module.h"
#include "llvm/IR/Verifier.h" #include "llvm/IR/Verifier.h"
#include "llvm/IR/DIBuilder.h" #include "llvm/IR/DIBuilder.h"
#include "llvm/Bitcode/BitcodeReader.h"
#include "llvm/ExecutionEngine/Orc/ThreadSafeModule.h" #include "llvm/ExecutionEngine/Orc/ThreadSafeModule.h"
@ -23,6 +22,17 @@
using namespace llvm; using namespace llvm;
using llvm::orc::ThreadSafeContext;
using llvm::orc::ThreadSafeModule;
extern "C" void NativityLLVMInitializeAll()
{
InitializeAllTargetInfos();
InitializeAllTargets();
InitializeAllTargetMCs();
InitializeAllAsmParsers();
InitializeAllAsmPrinters();
}
extern "C" LLVMContext* NativityLLVMCreateContext() extern "C" LLVMContext* NativityLLVMCreateContext()
{ {
@ -34,6 +44,10 @@ extern "C" Module* NativityLLVMCreateModule(const char* name_ptr, size_t name_le
{ {
auto name = StringRef(name_ptr, name_len); auto name = StringRef(name_ptr, name_len);
auto* module = new Module(name, context); auto* module = new Module(name, context);
// module->addModuleFlag(Module::Max, "Dwarf Version", 5);
// module->addModuleFlag(Module::Warning, "Debug Info Version", 3);
// module->addModuleFlag(Module::Max, "frame-pointer", 2);
return module; return module;
} }
@ -102,6 +116,16 @@ extern "C" void NativityLLVMBuilderSetCurrentDebugLocation(IRBuilder<>& builder,
builder.SetCurrentDebugLocation(debug_location); builder.SetCurrentDebugLocation(debug_location);
} }
extern "C" void NativityLLVMBuilderClearCurrentDebugLocation(IRBuilder<>&builder)
{
builder.SetCurrentDebugLocation(DebugLoc());
}
extern "C" void NativityLLVMBuilderSetInstructionDebugLocation(IRBuilder<>& builder, Instruction* instruction)
{
builder.SetInstDebugLocation(instruction);
}
extern "C" DIExpression* NativityLLVMDebugInfoBuilderCreateExpression(DIBuilder& builder, uint64_t* address, size_t length) extern "C" DIExpression* NativityLLVMDebugInfoBuilderCreateExpression(DIBuilder& builder, uint64_t* address, size_t length)
{ {
auto expr = ArrayRef<uint64_t>(address, length); auto expr = ArrayRef<uint64_t>(address, length);
@ -118,6 +142,11 @@ extern "C" DIGlobalVariableExpression* NativityLLVMDebugInfoBuilderCreateGlobalV
return global_variable; return global_variable;
} }
extern "C" void NativityLLVMDebugInfoGlobalVariableAddDebugInfo(GlobalVariable& global_variable, DIGlobalVariableExpression* global_variable_expression)
{
global_variable.addDebugInfo(global_variable_expression);
}
extern "C" DILocalVariable* NativityLLVMDebugInfoBuilderCreateParameterVariable(DIBuilder& builder, DIScope* scope, const char* name_ptr, size_t name_len, unsigned argument_index, DIFile* file, unsigned line_number, DIType* type, bool always_preserve, DINode::DIFlags flags) extern "C" DILocalVariable* NativityLLVMDebugInfoBuilderCreateParameterVariable(DIBuilder& builder, DIScope* scope, const char* name_ptr, size_t name_len, unsigned argument_index, DIFile* file, unsigned line_number, DIType* type, bool always_preserve, DINode::DIFlags flags)
{ {
assert(isa<DILocalScope>(scope)); assert(isa<DILocalScope>(scope));
@ -145,6 +174,7 @@ extern "C" DIType* NativityLLVMDebugInfoBuilderCreateBasicType(DIBuilder& builde
{ {
auto name = StringRef(name_ptr, name_len); auto name = StringRef(name_ptr, name_len);
auto* type = builder.createBasicType(name, bit_count, dwarf_encoding, flags); auto* type = builder.createBasicType(name, bit_count, dwarf_encoding, flags);
type->getName();
return type; return type;
} }
@ -214,11 +244,25 @@ extern "C" DIDerivedType* NativityLLVMDebugInfoBuilderCreateMemberType(DIBuilder
return member_type; return member_type;
} }
extern "C" DIDerivedType* NativityLLVMDebugInfoBuilderCreateBitfieldMemberType(DIBuilder& builder, DIScope *scope, const char* name_ptr, size_t name_len, DIFile* file, unsigned line_number, uint64_t bit_size, uint64_t bit_offset, uint64_t storage_bit_offset, DINode::DIFlags flags, DIType* type)
{
auto name = StringRef(name_ptr, name_len);
auto* member_type = builder.createBitFieldMemberType(scope, name, file, line_number, bit_size, bit_offset, storage_bit_offset, flags, type);
return member_type;
}
extern "C" bool NativityLLLVMDITypeIsResolved(DIType* type) extern "C" bool NativityLLLVMDITypeIsResolved(DIType* type)
{ {
return type->isResolved(); return type->isResolved();
} }
extern "C" void NativityLLLVMDITypeGetName(DIType& type, const char** name_pointer, size_t* name_length)
{
auto name = type.getName();
*name_pointer = name.data();
*name_length = name.size();
}
extern "C" DISubprogram* NativityLLVMDebugInfoScopeToSubprogram(DIScope* scope) extern "C" DISubprogram* NativityLLVMDebugInfoScopeToSubprogram(DIScope* scope)
{ {
auto* subprogram = dyn_cast<DISubprogram>(scope); auto* subprogram = dyn_cast<DISubprogram>(scope);
@ -287,6 +331,14 @@ extern "C" StructType* NativityLLVMGetStructType(LLVMContext& context, Type** ty
return struct_type; return struct_type;
} }
extern "C" StructType* NativityLLVMCreateStructType(LLVMContext& context, Type** type_ptr, size_t type_count, const char* name_pointer, size_t name_length, bool is_packed)
{
auto types = ArrayRef<Type*>(type_ptr, type_count);
auto name = StringRef(name_pointer, name_length);
auto* struct_type = StructType::create(context, types, name, is_packed);
return struct_type;
}
extern "C" LLVMContext* NativityLLVMTypeGetContext(Type& type) extern "C" LLVMContext* NativityLLVMTypeGetContext(Type& type)
{ {
auto& context = type.getContext(); auto& context = type.getContext();
@ -354,6 +406,12 @@ extern "C" Type* NativityLLVMValueGetType(Value* value)
return type; return type;
} }
extern "C" LLVMContext* NativityLLVMValueGetContext(Value& value)
{
auto& context = value.getContext();
return &context;
}
extern "C" PoisonValue* NativityLLVMGetPoisonValue(Type* type) extern "C" PoisonValue* NativityLLVMGetPoisonValue(Type* type)
{ {
auto* poison_value = PoisonValue::get(type); auto* poison_value = PoisonValue::get(type);
@ -438,6 +496,13 @@ extern "C" Value* NativityLLVMBuilderCreateICmp(IRBuilder<>& builder, CmpInst::P
return icmp; return icmp;
} }
extern "C" Value* NativityLLVMBuilderCreateIsNotNull(IRBuilder<>& builder, Value* value, const char* name_ptr, size_t name_len)
{
auto name = StringRef(name_ptr, name_len);
auto* not_null = builder.CreateIsNotNull(value, name);
return not_null;
}
extern "C" LoadInst* NativityLLVMBuilderCreateLoad(IRBuilder<>& builder, Type* type, Value* pointer, bool is_volatile, const char* name_ptr, size_t name_len, uint32_t alignment) extern "C" LoadInst* NativityLLVMBuilderCreateLoad(IRBuilder<>& builder, Type* type, Value* pointer, bool is_volatile, const char* name_ptr, size_t name_len, uint32_t alignment)
{ {
auto align = Align{alignment}; auto align = Align{alignment};
@ -589,13 +654,6 @@ extern "C" Value* NativityLLVMBuilderCreateGEP(IRBuilder<>& builder, Type* type,
return GEP; return GEP;
} }
extern "C" Value* NativityLLVMBuilderCreateStructGEP(IRBuilder<>& builder, Type* type, Value* pointer, unsigned index, const char* name_ptr, size_t name_len)
{
auto name = StringRef(name_ptr, name_len);
auto* gep = builder.CreateStructGEP(type, pointer, index, name);
return gep;
}
extern "C" BranchInst* NativityLLVMBuilderCreateBranch(IRBuilder<>& builder, BasicBlock* basic_block) extern "C" BranchInst* NativityLLVMBuilderCreateBranch(IRBuilder<>& builder, BasicBlock* basic_block)
{ {
auto* conditional_branch = builder.CreateBr(basic_block); auto* conditional_branch = builder.CreateBr(basic_block);
@ -787,6 +845,12 @@ extern "C" Function* NativityLLVMValueToFunction(Value* value)
return function; return function;
} }
extern "C" BasicBlock* NativityLLVMValueToBasicBlock(Value* value)
{
auto* basic_block = dyn_cast<BasicBlock>(value);
return basic_block;
}
extern "C" bool NativityLLVMTypeIsPointer(Type* type) extern "C" bool NativityLLVMTypeIsPointer(Type* type)
{ {
bool is_pointer = type->isPointerTy(); bool is_pointer = type->isPointerTy();
@ -893,14 +957,6 @@ extern "C" void NativityLLVMCallSetCallingConvention(CallBase& call_instruction,
call_instruction.setCallingConv(calling_convention); call_instruction.setCallingConv(calling_convention);
} }
extern "C" void NativityLLVMInitializeCodeGeneration()
{
InitializeAllTargetInfos();
InitializeAllTargets();
InitializeAllTargetMCs();
InitializeAllAsmParsers();
InitializeAllAsmPrinters();
}
extern "C" const Target* NativityLLVMGetTarget(const char* target_triple_ptr, size_t target_triple_len, const char** message_ptr, size_t* message_len) extern "C" const Target* NativityLLVMGetTarget(const char* target_triple_ptr, size_t target_triple_len, const char** message_ptr, size_t* message_len)
{ {
@ -920,20 +976,19 @@ extern "C" const Target* NativityLLVMGetTarget(const char* target_triple_ptr, si
return target; return target;
} }
// TODO: extern "C" TargetMachine* NativityLLVMTargetCreateTargetMachine(Target& target, const char* target_triple_ptr, size_t target_triple_len, const char* cpu_ptr, size_t cpu_len, const char* features_ptr, size_t features_len, Reloc::Model relocation_model, CodeModel::Model maybe_code_model, bool is_code_model_present, CodeGenOptLevel optimization_level, bool jit)
// extern "C" TargetMachine* NativityLLVMTargetCreateTargetMachine(Target& target, const char* target_triple_ptr, size_t target_triple_len, const char* cpu_ptr, size_t cpu_len, const char* features_ptr, size_t features_len, Reloc::Model relocation_model, CodeModel::Model maybe_code_model, bool is_code_model_present, CodeGenOpt::Level optimization_level, bool jit) {
// { auto target_triple = StringRef(target_triple_ptr, target_triple_len);
// auto target_triple = StringRef(target_triple_ptr, target_triple_len); auto cpu = StringRef(cpu_ptr, cpu_len);
// auto cpu = StringRef(cpu_ptr, cpu_len); auto features = StringRef(features_ptr, features_len);
// auto features = StringRef(features_ptr, features_len); TargetOptions target_options;
// TargetOptions target_options; std::optional<CodeModel::Model> code_model = std::nullopt;
// std::optional<CodeModel::Model> code_model = std::nullopt; if (is_code_model_present) {
// if (is_code_model_present) { code_model = maybe_code_model;
// code_model = maybe_code_model; }
// } TargetMachine* target_machine = target.createTargetMachine(target_triple, cpu, features, target_options, relocation_model, code_model, optimization_level, jit);
// TargetMachine* target_machine = target.createTargetMachine(target_triple, cpu, features, target_options, relocation_model, code_model, optimization_level, jit); return target_machine;
// return target_machine; }
// }
extern "C" void NativityLLVMModuleSetTargetMachineDataLayout(Module& module, TargetMachine& target_machine) extern "C" void NativityLLVMModuleSetTargetMachineDataLayout(Module& module, TargetMachine& target_machine)
{ {
@ -1053,18 +1108,26 @@ extern "C" AttributeSet NativityLLVMContextGetAttributeSet(LLVMContext& context,
return attribute_set; return attribute_set;
} }
extern "C" void NativityLLVMFunctionSetAttributes(Function& function, LLVMContext& context, AttributeSet function_attributes, AttributeSet return_attributes, const AttributeSet* parameter_attribute_set_ptr, size_t parameter_attribute_set_count) static AttributeList get_attribute_list(LLVMContext& context, AttributeSet function_attributes, AttributeSet return_attributes, const AttributeSet* parameter_attribute_set_ptr, size_t parameter_attribute_set_count)
{ {
auto parameter_attribute_sets = ArrayRef<AttributeSet>(parameter_attribute_set_ptr, parameter_attribute_set_count); auto parameter_attribute_sets = ArrayRef<AttributeSet>(parameter_attribute_set_ptr, parameter_attribute_set_count);
auto attribute_list = AttributeList::get(context, function_attributes, return_attributes, parameter_attribute_sets); auto attribute_list = AttributeList::get(context, function_attributes, return_attributes, parameter_attribute_sets);
function.setAttributes(attribute_list); return attribute_list;
}
extern "C" void NativityLLVMFunctionSetAttributes(Function& function, LLVMContext& context, AttributeSet function_attributes, AttributeSet return_attributes, const AttributeSet* parameter_attribute_set_ptr, size_t parameter_attribute_set_count)
{
function.setAttributes(get_attribute_list(context, function_attributes, return_attributes, parameter_attribute_set_ptr, parameter_attribute_set_count));
} }
extern "C" void NativityLLVMCallSetAttributes(CallInst& call, LLVMContext& context, AttributeSet function_attributes, AttributeSet return_attributes, const AttributeSet* parameter_attribute_set_ptr, size_t parameter_attribute_set_count) extern "C" void NativityLLVMCallSetAttributes(CallInst& call, LLVMContext& context, AttributeSet function_attributes, AttributeSet return_attributes, const AttributeSet* parameter_attribute_set_ptr, size_t parameter_attribute_set_count)
{ {
auto parameter_attribute_sets = ArrayRef<AttributeSet>(parameter_attribute_set_ptr, parameter_attribute_set_count); call.setAttributes(get_attribute_list(context, function_attributes, return_attributes, parameter_attribute_set_ptr, parameter_attribute_set_count));
auto attribute_list = AttributeList::get(context, function_attributes, return_attributes, parameter_attribute_sets); }
call.setAttributes(attribute_list); extern "C" void NativityLLVMGlobalObjectSetAlignment(GlobalObject& global_object, uint32_t alignment)
{
Align align(alignment);
global_object.setAlignment(align);
} }
extern "C" CallInst* NativityLLVMBuilderCreateMemcpy(IRBuilder<>& builder, Value* destination, uint32_t destination_alignment, Value* source, uint32_t source_alignment, uint64_t size, bool is_volatile) extern "C" CallInst* NativityLLVMBuilderCreateMemcpy(IRBuilder<>& builder, Value* destination, uint32_t destination_alignment, Value* source, uint32_t source_alignment, uint64_t size, bool is_volatile)
@ -1076,6 +1139,13 @@ extern "C" CallInst* NativityLLVMBuilderCreateMemcpy(IRBuilder<>& builder, Value
return memcpy; return memcpy;
} }
extern "C" bool NativityLLVMLinkModules(Module& destination, Module* source)
{
auto src = std::unique_ptr<Module>(source);
bool result = Linker::linkModules(destination, std::move(src));
// Invert the condition because LLVM boolean concept is lame
return !result;
}
extern "C" void NativityLLVMTypeAssertEqual(Type* a, Type* b) extern "C" void NativityLLVMTypeAssertEqual(Type* a, Type* b)
{ {
assert(a == b); assert(a == b);

View File

@ -2726,6 +2726,7 @@ void run_c_tests(void) {
{ {
assert_or_panic(nat_ret_bool() == 1); assert_or_panic(nat_ret_bool() == 1);
assert_or_panic(nat_ret_u8() == 0xff); assert_or_panic(nat_ret_u8() == 0xff);
assert_or_panic(nat_ret_u16() == 0xffff); assert_or_panic(nat_ret_u16() == 0xffff);
assert_or_panic(nat_ret_u32() == 0xffffffff); assert_or_panic(nat_ret_u32() == 0xffffffff);
@ -5423,35 +5424,35 @@ typedef struct {
// } // }
// #endif // #endif
void __attribute__((stdcall)) stdcall_scalars(char a, short b, int c, float d, double e) { // void __attribute__((stdcall)) stdcall_scalars(char a, short b, int c, float d, double e) {
assert_or_panic(a == 1); // assert_or_panic(a == 1);
assert_or_panic(b == 2); // assert_or_panic(b == 2);
assert_or_panic(c == 3); // assert_or_panic(c == 3);
assert_or_panic(d == 4.0); // assert_or_panic(d == 4.0);
assert_or_panic(e == 5.0); // assert_or_panic(e == 5.0);
} // }
//
typedef struct { // typedef struct {
short x; // short x;
short y; // short y;
} Coord2; // } Coord2;
//
Coord2 __attribute__((stdcall)) stdcall_coord2(Coord2 a, Coord2 b, Coord2 c) { // Coord2 __attribute__((stdcall)) stdcall_coord2(Coord2 a, Coord2 b, Coord2 c) {
assert_or_panic(a.x == 0x1111); // assert_or_panic(a.x == 0x1111);
assert_or_panic(a.y == 0x2222); // assert_or_panic(a.y == 0x2222);
assert_or_panic(b.x == 0x3333); // assert_or_panic(b.x == 0x3333);
assert_or_panic(b.y == 0x4444); // assert_or_panic(b.y == 0x4444);
assert_or_panic(c.x == 0x5555); // assert_or_panic(c.x == 0x5555);
assert_or_panic(c.y == 0x6666); // assert_or_panic(c.y == 0x6666);
return (Coord2){123, 456}; // return (Coord2){123, 456};
} // }
//
void __attribute__((stdcall)) stdcall_big_union(union BigUnion x) { // void __attribute__((stdcall)) stdcall_big_union(union BigUnion x) {
assert_or_panic(x.a.a == 1); // assert_or_panic(x.a.a == 1);
assert_or_panic(x.a.b == 2); // assert_or_panic(x.a.b == 2);
assert_or_panic(x.a.c == 3); // assert_or_panic(x.a.c == 3);
assert_or_panic(x.a.d == 4); // assert_or_panic(x.a.d == 4);
} // }
#ifdef __x86_64__ #ifdef __x86_64__
struct ByRef __attribute__((ms_abi)) c_explict_win64(struct ByRef in) { struct ByRef __attribute__((ms_abi)) c_explict_win64(struct ByRef in) {