├── test.rf ├── third-party ├── lib │ └── LLVM-C.lib └── include │ ├── llvm-c │ ├── module.modulemap │ ├── Transforms │ │ ├── InstCombine.h │ │ ├── AggressiveInstCombine.h │ │ ├── Vectorize.h │ │ ├── Utils.h │ │ ├── Coroutines.h │ │ ├── PassManagerBuilder.h │ │ ├── IPO.h │ │ ├── PassBuilder.h │ │ └── Scalar.h │ ├── IRReader.h │ ├── Linker.h │ ├── Deprecated.h │ ├── ExternC.h │ ├── ErrorHandling.h │ ├── Initialization.h │ ├── BitWriter.h │ ├── Support.h │ ├── Error.h │ ├── OrcEE.h │ ├── Analysis.h │ ├── Comdat.h │ ├── DataTypes.h │ ├── BitReader.h │ ├── Disassembler.h │ ├── Types.h │ ├── TargetMachine.h │ ├── DisassemblerTypes.h │ ├── ExecutionEngine.h │ ├── Object.h │ └── LLJIT.h │ └── llvm │ └── Config │ ├── Targets.def.in │ ├── AsmParsers.def.in │ ├── AsmPrinters.def.in │ ├── Disassemblers.def.in │ ├── Targets.def │ ├── AsmParsers.def │ ├── Disassemblers.def │ ├── AsmPrinters.def │ ├── abi-breaking.h │ ├── abi-breaking.h.cmake │ ├── llvm-config.h │ └── llvm-config.h.cmake ├── ALL_BUILD.vcxproj.user ├── grammar.txt ├── source ├── base │ ├── base.h │ ├── utils.h │ ├── log.h │ ├── str.h │ ├── mem.h │ ├── utils.c │ ├── vmath.h │ └── ds.h ├── types.h ├── parser.h ├── tables.h ├── checker.h ├── llvm_emitter.h ├── ast_nodes.h ├── vm.h ├── main.c ├── lexer.h ├── defines.h ├── checker.c ├── vm.c ├── llvm_emitter.c └── parser.c ├── Rift.vcxproj.user ├── .gitignore ├── README.md ├── project.4coder ├── examples └── basics.rf ├── LICENSE.md └── CMakeLists.txt /test.rf: -------------------------------------------------------------------------------- 1 | print (11 + 12 * 13) 2 | -------------------------------------------------------------------------------- /third-party/lib/LLVM-C.lib: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PixelRifts/Rift/HEAD/third-party/lib/LLVM-C.lib -------------------------------------------------------------------------------- /third-party/include/llvm-c/module.modulemap: -------------------------------------------------------------------------------- 1 | module LLVM_C { 2 | umbrella "." 3 | module * { export * } 4 | } 5 | -------------------------------------------------------------------------------- /ALL_BUILD.vcxproj.user: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /grammar.txt: -------------------------------------------------------------------------------- 1 | 2 | Expr -> (Expr) 3 | | Term [+ -] Factor 4 | | Term 5 | 6 | Term -> Factor [* / %] Number 7 | | Factor 8 | 9 | Factor -> (Number) 10 | | [+ -] Number 11 | | Number 12 | -------------------------------------------------------------------------------- /source/base/base.h: -------------------------------------------------------------------------------- 1 | /* date = July 3rd 2022 11:23 am */ 2 | 3 | #ifndef BASE_H 4 | #define BASE_H 5 | 6 | #include "defines.h" 7 | #include "ds.h" 8 | #include "log.h" 9 | #include "mem.h" 10 | #include "str.h" 11 | #include "utils.h" 12 | #include "vmath.h" 13 | 14 | #endif //BASE_H 15 | -------------------------------------------------------------------------------- /Rift.vcxproj.user: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | ./test.rf 5 | WindowsLocalDebugger 6 | 7 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .vs/ 2 | bin/ 3 | *.ll 4 | *.exe 5 | *.o 6 | example.bat 7 | generated.* 8 | .vscode 9 | *.sln 10 | *.vcxproj 11 | *.vcxproj.filters 12 | *.proj 13 | *.proj.filters 14 | ./Rift 15 | 16 | CMakeLists.txt.user 17 | CMakeCache.txt 18 | CMakeFiles 19 | CMakeScripts 20 | Testing 21 | Makefile 22 | cmake_install.cmake 23 | install_manifest.txt 24 | compile_commands.json 25 | CTestTestfile.cmake 26 | _deps 27 | build/ 28 | Rift.dir 29 | Debug -------------------------------------------------------------------------------- /source/types.h: -------------------------------------------------------------------------------- 1 | /* date = October 8th 2022 4:51 pm */ 2 | 3 | #ifndef TYPES_H 4 | #define TYPES_H 5 | 6 | //~ 7 | 8 | typedef struct Type Type; 9 | 10 | typedef u32 TypeKind; 11 | enum { 12 | TypeKind_Invalid, 13 | TypeKind_Regular, 14 | TypeKind_COUNT, 15 | }; 16 | 17 | typedef u32 RegularTypeKind; 18 | enum { 19 | RegularTypeKind_Invalid, 20 | RegularTypeKind_Integer, 21 | RegularTypeKind_COUNT, 22 | }; 23 | 24 | 25 | struct Type { 26 | TypeKind kind; 27 | union { 28 | RegularTypeKind regular; 29 | }; 30 | }; 31 | 32 | typedef u64 TypeID; 33 | 34 | #endif //TYPES_H 35 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Rift 2 | Rift - A Language Compiler 3 | 4 | Important! 5 | ***Master branch is WIP (Compiler rework)*** 6 | 7 | Check out branch v1 for the old transpiler 8 | 9 | Linux support for v2 coming soon :tm: 10 | 11 | Meant to be C-Like with some helpful features. 12 | - Syntax is similar to C 13 | - Transpiles to C code 14 | 15 | ## Getting Started 16 | (NOTE FOR LINUX USERS): Install `llvm llvm-dev zlib1g-dev` before compiling 17 | 18 | 1) Clone the Repo to your machine 19 | 2) Make a bin directory in the repo root 20 | 3) Build project using build.bat 21 | 4) (temporary) Compile example test.rf to blah.ll, use `clang -g blah.ll -o test.exe` to compile the IR to an executable 22 | -------------------------------------------------------------------------------- /source/parser.h: -------------------------------------------------------------------------------- 1 | /* date = October 4th 2022 7:49 pm */ 2 | 3 | #ifndef PARSER_H 4 | #define PARSER_H 5 | 6 | #include "base/mem.h" 7 | #include "lexer.h" 8 | 9 | #include "ast_nodes.h" 10 | 11 | typedef u32 P_Precedence; 12 | enum { 13 | Prec_Invalid, 14 | 15 | Prec_Term, 16 | Prec_Factor, 17 | 18 | Prec_Max, 19 | }; 20 | 21 | typedef struct P_Parser { 22 | L_Token prev; 23 | L_Token curr; 24 | L_Token next; 25 | 26 | L_Lexer* lexer; 27 | M_Pool* ast_node_pool; 28 | 29 | b8 panic_mode; 30 | } P_Parser; 31 | 32 | 33 | IR_Ast* P_ParseExpr(P_Parser* p, P_Precedence prec); 34 | IR_Ast* P_ParseStmt(P_Parser* p); 35 | IR_Ast* P_Parse(P_Parser* p); 36 | 37 | void P_Init(P_Parser* p, L_Lexer* lexer); 38 | void P_Free(P_Parser* p); 39 | 40 | #endif //PARSER_H 41 | -------------------------------------------------------------------------------- /source/base/utils.h: -------------------------------------------------------------------------------- 1 | /* date = March 11th 2022 2:07 pm */ 2 | 3 | #ifndef UTILS_H 4 | #define UTILS_H 5 | 6 | #include "defines.h" 7 | #include "mem.h" 8 | #include "str.h" 9 | 10 | //~ Time 11 | 12 | typedef u64 U_DenseTime; 13 | 14 | typedef struct U_DateTime { 15 | u16 ms; 16 | u8 sec; 17 | u8 minute; 18 | u8 hour; 19 | u8 day; 20 | u8 month; 21 | s32 year; 22 | } U_DateTime; 23 | 24 | U_DenseTime U_DenseTimeFromDateTime(U_DateTime* datetime); 25 | U_DateTime U_DateTimeFromDenseTime(U_DenseTime densetime); 26 | 27 | //~ Filepaths 28 | 29 | string U_FixFilepath(M_Arena* arena, string filepath); 30 | string U_GetFullFilepath(M_Arena* arena, string filename); 31 | string U_GetFilenameFromFilepath(string filepath); 32 | string U_GetDirectoryFromFilepath(string filepath); 33 | 34 | #endif //UTILS_H 35 | -------------------------------------------------------------------------------- /source/tables.h: -------------------------------------------------------------------------------- 1 | /* date = October 9th 2022 9:33 pm */ 2 | 3 | #ifndef TABLES_H 4 | #define TABLES_H 5 | 6 | // NOTE(voxel): All operator tables are 0 terminated 7 | 8 | typedef struct TypePair { 9 | TypeID a; 10 | TypeID r; 11 | } TypePair; 12 | 13 | typedef struct TypeTriple { 14 | TypeID a; 15 | TypeID b; 16 | TypeID r; 17 | } TypeTriple; 18 | 19 | TypePair unary_operator_table_plusminus[] = { 20 | { TypeID_Integer, TypeID_Integer }, 21 | 22 | { TypeID_Invalid, TypeID_Invalid }, 23 | }; 24 | 25 | TypeTriple binary_operator_table_plusminus[] = { 26 | { TypeID_Integer, TypeID_Integer, TypeID_Integer }, 27 | 28 | { TypeID_Invalid, TypeID_Invalid, TypeID_Invalid }, 29 | }; 30 | 31 | TypeTriple binary_operator_table_stardivmod[] = { 32 | { TypeID_Integer, TypeID_Integer, TypeID_Integer }, 33 | 34 | { TypeID_Invalid, TypeID_Invalid, TypeID_Invalid }, 35 | }; 36 | 37 | #endif //TABLES_H 38 | -------------------------------------------------------------------------------- /project.4coder: -------------------------------------------------------------------------------- 1 | version(1); 2 | 3 | project_name = "Rift Transpiler"; 4 | 5 | patterns = 6 | { 7 | "*.c", 8 | "*.rf", 9 | "*.cpp", 10 | "*.mdesk", 11 | "*.h", 12 | "*.bat", 13 | "*.sh", 14 | "*.4coder", 15 | "*.txt", 16 | }; 17 | 18 | blacklist_patterns = 19 | { 20 | ".*", 21 | }; 22 | 23 | load_paths_custom = { 24 | { "." } 25 | }; 26 | 27 | load_paths = { 28 | { load_paths_custom, .os = "win" }, 29 | }; 30 | 31 | command_list = 32 | { 33 | { 34 | .name = "build", 35 | .out = "*compilation*", 36 | .footer_panel = true, 37 | .save_dirty_files = true, 38 | .cursor_at_end = true, 39 | .cmd = 40 | { 41 | { "build.bat", .os = "win" }, 42 | }, 43 | }, 44 | { 45 | .name = "run", 46 | .out = "*compilation*", 47 | .footer_panel = true, 48 | .save_dirty_files = true, 49 | .cursor_at_end = true, 50 | .cmd = 51 | { 52 | { "Debug\rift.exe ./test.rf", .os = "win" }, 53 | }, 54 | }, 55 | }; 56 | 57 | fkey_command[1] = "build"; 58 | fkey_command[2] = "run"; 59 | -------------------------------------------------------------------------------- /examples/basics.rf: -------------------------------------------------------------------------------- 1 | // Simple Declaration: 2 | // name : type = value; 3 | // type can be inferred from value in which case: 4 | // name := value; 5 | 6 | // Native declarations 7 | 8 | printf := func(str : cstring, data : ...) -> int #native; 9 | puts := func(str : cstring) -> int #native; 10 | 11 | // Lambda expressions are the way to define functions. 12 | // func(param1 : type1, param2 : type2) [-> return_type] body 13 | // body can be a block statement or any regular statement 14 | 15 | add := func(a : int, b : int) -> int return a + b; 16 | 17 | // Entry point 18 | 19 | main := func() -> int { 20 | i := 0; 21 | j := 10; 22 | k := 20; 23 | 24 | l := add(i, add(j, k)); 25 | 26 | printf("%lld\n", l); 27 | 28 | if l == 30 { 29 | tau := 0; 30 | while tau < 10 { 31 | tau++; 32 | printf("%lld ", tau); 33 | } 34 | printf("\n"); 35 | } else { 36 | puts("Not thirty"); 37 | } 38 | 39 | return 0; 40 | } -------------------------------------------------------------------------------- /source/checker.h: -------------------------------------------------------------------------------- 1 | /* date = October 8th 2022 4:34 pm */ 2 | 3 | #ifndef CHECKER_H 4 | #define CHECKER_H 5 | 6 | #include "ast_nodes.h" 7 | #include "types.h" 8 | #include "base/ds.h" 9 | 10 | //~ Type Cache 11 | 12 | DArray_Prototype(Type); 13 | 14 | #if 0 15 | typedef struct TypeCache TypeCache; 16 | #endif 17 | typedef darray(Type) TypeCache; 18 | 19 | // TODO(voxel): Switch to hashset 20 | //typedef struct TypeCache { 21 | //u32 len; 22 | //u32 cap; 23 | //Type* elems; 24 | //} TypeCache; 25 | 26 | void TypeCache_Init(TypeCache* cache); 27 | TypeID TypeCache_Register(TypeCache* cache, Type type); 28 | Type* TypeCache_Get(TypeCache* cache, TypeID id); 29 | void TypeCache_Free(TypeCache* cache); 30 | 31 | enum { 32 | TypeID_Invalid = 0, 33 | TypeID_Integer, 34 | TypeID_COUNT, 35 | }; 36 | 37 | //~ Checker 38 | 39 | typedef struct C_Checker { 40 | IR_Ast* ast; 41 | b8 errored; 42 | 43 | TypeCache type_cache; 44 | } C_Checker; 45 | 46 | void C_Init(C_Checker* checker, IR_Ast* ast); 47 | b8 C_Check(C_Checker* checker); 48 | void C_Free(C_Checker* checker); 49 | 50 | #endif //CHECKER_H 51 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2021 VoxelRifts 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. -------------------------------------------------------------------------------- /source/llvm_emitter.h: -------------------------------------------------------------------------------- 1 | /* date = October 10th 2022 9:04 pm */ 2 | 3 | #ifndef LLVM_EMITTER_H 4 | #define LLVM_EMITTER_H 5 | 6 | #include "ast_nodes.h" 7 | #include "llvm-c/Core.h" 8 | 9 | #if 0 10 | typedef struct LLVMModuleRef LLVMModuleRef; 11 | typedef struct LLVMTypeRef LLVMTypeRef; 12 | typedef struct LLVMValueRef LLVMValueRef; 13 | typedef struct LLVMBuilderRef LLVMBuilderRef; 14 | typedef struct LLVMTargetRef LLVMTargetRef; 15 | typedef struct LLVMTargetMachineRef LLVMTargetMachineRef; 16 | typedef struct LLVMTargetDataRef LLVMTargetDataRef; 17 | typedef struct LLVMContextRef LLVMContextRef; 18 | typedef struct LLVMBasicBlockRef LLVMBasicBlockRef; 19 | #endif 20 | 21 | typedef struct LLVM_Emitter { 22 | LLVMContextRef context; 23 | LLVMModuleRef module; 24 | LLVMBuilderRef builder; 25 | 26 | LLVMTypeRef int_8_type; 27 | LLVMTypeRef int_8_type_ptr; 28 | LLVMTypeRef int_32_type; 29 | 30 | LLVMTypeRef printf_type; 31 | LLVMValueRef printf_object; 32 | } LLVM_Emitter; 33 | 34 | LLVMValueRef LLVM_Emit(LLVM_Emitter* emitter, IR_Ast* ast); 35 | 36 | void LLVM_Init(LLVM_Emitter* emitter); 37 | void LLVM_Free(LLVM_Emitter* emitter); 38 | 39 | #endif //LLVM_EMITTER_H 40 | -------------------------------------------------------------------------------- /CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 3.11) 2 | project(Rift) 3 | set(CMAKE_C_STANDARD 11) # Enable c11 standard 4 | 5 | file(GLOB_RECURSE SOURCE_FILES CONFIGURE_DEPENDS source/*.c source/*.h) 6 | 7 | add_executable(Rift ${SOURCE_FILES}) 8 | target_include_directories(Rift PRIVATE source/) 9 | 10 | if(MSVC) 11 | target_include_directories(Rift PRIVATE third-party/include/) 12 | target_link_directories(Rift PRIVATE third-party/lib/) 13 | target_link_libraries(Rift LLVM-C) 14 | add_definitions(-D_CRT_SECURE_NO_WARNINGS) 15 | add_definitions(/Zc:preprocessor) 16 | endif() 17 | if(UNIX) 18 | find_package(LLVM REQUIRED CONFIG) 19 | message(STATUS, "${LLVM_INCLUDE_DIRS}") 20 | include_directories(${LLVM_INCLUDE_DIRS}) 21 | target_include_directories(Rift PRIVATE third-party/lib) 22 | add_definitions(${LLVM_DEFINITIONS}) 23 | llvm_map_components_to_libnames(llvm_libs 24 | Analysis 25 | Core 26 | ExecutionEngine 27 | InstCombine 28 | Object 29 | OrcJIT 30 | RuntimeDyld 31 | ScalarOpts 32 | Support 33 | native) 34 | target_link_libraries(Rift ${llvm_libs} m) 35 | endif() -------------------------------------------------------------------------------- /source/ast_nodes.h: -------------------------------------------------------------------------------- 1 | /* date = October 5th 2022 5:54 pm */ 2 | 3 | #ifndef AST_NODES_H 4 | #define AST_NODES_H 5 | 6 | #include "defines.h" 7 | #include "lexer.h" 8 | 9 | //~ Ast node definitions 10 | 11 | typedef struct IR_Ast IR_Ast; 12 | 13 | typedef struct IR_AstExprIntLiteral { 14 | i32 value; 15 | } IR_AstIntLiteral; 16 | 17 | typedef struct IR_AstExprFloatLiteral { 18 | f32 value; 19 | } IR_AstFloatLiteral; 20 | 21 | typedef struct IR_AstExprUnary { 22 | L_Token operator; 23 | IR_Ast* operand; 24 | } IR_AstExprUnary; 25 | 26 | typedef struct IR_AstExprBinary { 27 | L_Token operator; 28 | IR_Ast* a; 29 | IR_Ast* b; 30 | } IR_AstExprBinary; 31 | 32 | 33 | typedef struct IR_AstStmtPrint { 34 | IR_Ast* value; 35 | } IR_AstStmtPrint; 36 | 37 | //~ Ast struct definition 38 | 39 | typedef u32 IR_AstType; 40 | enum { 41 | AstType_IntLiteral, 42 | AstType_FloatLiteral, 43 | AstType_ExprUnary, 44 | AstType_ExprBinary, 45 | 46 | AstType_StmtPrint, 47 | 48 | AstType_COUNT, 49 | }; 50 | 51 | struct IR_Ast { 52 | IR_AstType type; 53 | 54 | union { 55 | IR_AstIntLiteral int_lit; 56 | IR_AstFloatLiteral float_lit; 57 | IR_AstExprUnary unary; 58 | IR_AstExprBinary binary; 59 | 60 | IR_AstStmtPrint print; 61 | }; 62 | }; 63 | 64 | #endif //AST_NODES_H 65 | -------------------------------------------------------------------------------- /source/vm.h: -------------------------------------------------------------------------------- 1 | /* date = October 6th 2022 7:05 pm */ 2 | 3 | #ifndef VM_H 4 | #define VM_H 5 | 6 | #include "ast_nodes.h" 7 | #include "base/ds.h" 8 | 9 | //~ Chunk Helpers 10 | 11 | DArray_Prototype(u8); 12 | 13 | #if 0 14 | typedef struct IR_Chunk IR_Chunk; 15 | #endif 16 | typedef darray(u8) IR_Chunk; 17 | 18 | IR_Chunk IR_ChunkAlloc(void); 19 | void IR_ChunkPushOp(IR_Chunk* chunk, u8 byte); 20 | void IR_ChunkPushU32(IR_Chunk* chunk, u32 value); 21 | void IR_ChunkPush(IR_Chunk* chunk, u8* bytes, u32 count); 22 | void IR_ChunkFree(IR_Chunk* chunk); 23 | 24 | //~ Opcodes and runtime values 25 | 26 | typedef u32 VM_Opcode; 27 | enum { 28 | Opcode_Nop, 29 | Opcode_Push, 30 | Opcode_Pop, 31 | Opcode_UnaryOp, 32 | Opcode_BinaryOp, 33 | Opcode_Print, 34 | 35 | Opcode_COUNT 36 | }; 37 | 38 | typedef u32 VM_RuntimeValueType; 39 | enum { 40 | RuntimeValueType_Invalid, 41 | RuntimeValueType_Integer, 42 | 43 | RuntimeValueType_COUNT, 44 | }; 45 | 46 | typedef struct VM_RuntimeValue { 47 | VM_RuntimeValueType type; 48 | 49 | union { 50 | i32 as_int; 51 | }; 52 | } VM_RuntimeValue; 53 | 54 | //~ VM Helpers 55 | 56 | Stack_Prototype(VM_RuntimeValue); 57 | 58 | void VM_Lower(IR_Chunk* chunk, IR_Ast* ast); 59 | IR_Chunk VM_LowerConstexpr(IR_Ast* ast); 60 | 61 | VM_RuntimeValue VM_RunExprChunk(IR_Chunk* chunk); 62 | 63 | #endif //VM_H 64 | -------------------------------------------------------------------------------- /source/base/log.h: -------------------------------------------------------------------------------- 1 | /* date = July 3rd 2022 11:22 am */ 2 | 3 | #ifndef LOG_H 4 | #define LOG_H 5 | 6 | #include "defines.h" 7 | 8 | #if defined(_DEBUG) 9 | # define Log(format, ...) Statement(\ 10 | printf("Info: ");\ 11 | printf(format, #__VA_ARGS__);\ 12 | printf("\n");\ 13 | flush;\ 14 | ) 15 | # define LogError(format, ...) Statement(\ 16 | printf("%s:%d: Error: ", FILE_NAME, __LINE__);\ 17 | printf(format, #__VA_ARGS__);\ 18 | printf("\n");\ 19 | flush;\ 20 | ) 21 | # define LogReturn(ret, format, ...) Statement(\ 22 | printf("%s:%d: Error: ", FILE_NAME, __LINE__);\ 23 | printf(format, #__VA_ARGS__);\ 24 | printf("\n");\ 25 | flush;\ 26 | return ret;\ 27 | ) 28 | # define LogFatal(format, ...) Statement(\ 29 | printf("%s:%d: Error: ", FILE_NAME, __LINE__);\ 30 | printf(format, #__VA_ARGS__);\ 31 | printf("\n");\ 32 | flush;\ 33 | exit(-1);\ 34 | ) 35 | # define AssertTrue(c, format, ...) Statement(\ 36 | if (!(c)) {\ 37 | printf("%s:%d: Error: ", FILE_NAME, __LINE__);\ 38 | printf("Assertion Failure: ");\ 39 | printf(format, #__VA_ARGS__);\ 40 | printf("\n");\ 41 | }\ 42 | ) 43 | #else 44 | # define Log(format, ...) Statement() 45 | # define LogError(format, ...) Statement() 46 | # define LogReturn(ret, format, ...) Statement() 47 | # define LogFatal(format, ...) Statement() 48 | # define AssertTrue(c, format, ...) Statement() 49 | #endif 50 | 51 | #endif //LOG_H 52 | -------------------------------------------------------------------------------- /third-party/include/llvm-c/Transforms/InstCombine.h: -------------------------------------------------------------------------------- 1 | /*===-- Scalar.h - Scalar Transformation Library C Interface ----*- C++ -*-===*\ 2 | |* *| 3 | |* Part of the LLVM Project, under the Apache License v2.0 with LLVM *| 4 | |* Exceptions. *| 5 | |* See https://llvm.org/LICENSE.txt for license information. *| 6 | |* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception *| 7 | |* *| 8 | |*===----------------------------------------------------------------------===*| 9 | |* *| 10 | |* This header declares the C interface to libLLVMInstCombine.a, which *| 11 | |* combines instructions to form fewer, simple IR instructions. *| 12 | |* *| 13 | \*===----------------------------------------------------------------------===*/ 14 | 15 | #ifndef LLVM_C_TRANSFORMS_INSTCOMBINE_H 16 | #define LLVM_C_TRANSFORMS_INSTCOMBINE_H 17 | 18 | #include "llvm-c/ExternC.h" 19 | #include "llvm-c/Types.h" 20 | 21 | LLVM_C_EXTERN_C_BEGIN 22 | 23 | /** 24 | * @defgroup LLVMCTransformsInstCombine Instruction Combining transformations 25 | * @ingroup LLVMCTransforms 26 | * 27 | * @{ 28 | */ 29 | 30 | /** See llvm::createInstructionCombiningPass function. */ 31 | void LLVMAddInstructionCombiningPass(LLVMPassManagerRef PM); 32 | 33 | /** 34 | * @} 35 | */ 36 | 37 | LLVM_C_EXTERN_C_END 38 | 39 | #endif 40 | 41 | -------------------------------------------------------------------------------- /third-party/include/llvm-c/Transforms/AggressiveInstCombine.h: -------------------------------------------------------------------------------- 1 | /*===-- AggressiveInstCombine.h ---------------------------------*- C++ -*-===*\ 2 | |* *| 3 | |* Part of the LLVM Project, under the Apache License v2.0 with LLVM *| 4 | |* Exceptions. *| 5 | |* See https://llvm.org/LICENSE.txt for license information. *| 6 | |* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception *| 7 | |* *| 8 | |*===----------------------------------------------------------------------===*| 9 | |* *| 10 | |* This header declares the C interface to libLLVMAggressiveInstCombine.a, *| 11 | |* which combines instructions to form fewer, simple IR instructions. *| 12 | |* *| 13 | \*===----------------------------------------------------------------------===*/ 14 | 15 | #ifndef LLVM_C_TRANSFORMS_AGGRESSIVEINSTCOMBINE_H 16 | #define LLVM_C_TRANSFORMS_AGGRESSIVEINSTCOMBINE_H 17 | 18 | #include "llvm-c/ExternC.h" 19 | #include "llvm-c/Types.h" 20 | 21 | LLVM_C_EXTERN_C_BEGIN 22 | 23 | /** 24 | * @defgroup LLVMCTransformsAggressiveInstCombine Aggressive Instruction Combining transformations 25 | * @ingroup LLVMCTransforms 26 | * 27 | * @{ 28 | */ 29 | 30 | /** See llvm::createAggressiveInstCombinerPass function. */ 31 | void LLVMAddAggressiveInstCombinerPass(LLVMPassManagerRef PM); 32 | 33 | /** 34 | * @} 35 | */ 36 | 37 | LLVM_C_EXTERN_C_END 38 | 39 | #endif 40 | 41 | -------------------------------------------------------------------------------- /source/main.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include "base/str.h" 4 | #include "base/mem.h" 5 | #include "base/utils.h" 6 | #include "lexer.h" 7 | #include "parser.h" 8 | #include "checker.h" 9 | #include "vm.h" 10 | #include "llvm_emitter.h" 11 | 12 | static char* readFile(const char* path) { 13 | FILE* file = fopen(path, "rb"); 14 | 15 | fseek(file, 0L, SEEK_END); 16 | size_t fileSize = ftell(file); 17 | rewind(file); 18 | 19 | char* buffer = (char*)malloc(fileSize + 1); 20 | size_t bytesRead = fread(buffer, sizeof(char), fileSize, file); 21 | buffer[bytesRead] = '\0'; 22 | 23 | fclose(file); 24 | return buffer; 25 | } 26 | 27 | int main(int argc, char **argv) { 28 | M_ScratchInit(); 29 | 30 | if (argc < 2) { 31 | printf("Did not recieve filename as first argument\n"); 32 | } else { 33 | char* source = readFile(argv[1]); 34 | string source_str = { .str = (u8*) source, .size = strlen(source) }; 35 | string source_filename = { .str = (u8*) argv[1], .size = strlen(argv[1]) }; 36 | 37 | L_Lexer lexer = {0}; 38 | P_Parser parser = {0}; 39 | L_Init(&lexer, source_str); 40 | P_Init(&parser, &lexer); 41 | 42 | IR_Ast* ast = P_Parse(&parser); 43 | 44 | C_Checker checker = {0}; 45 | C_Init(&checker, ast); 46 | if (C_Check(&checker)) { 47 | IR_Chunk chunk = VM_LowerConstexpr(ast); 48 | VM_RunExprChunk(&chunk); 49 | IR_ChunkFree(&chunk); 50 | 51 | LLVM_Emitter emitter = {0}; 52 | LLVM_Init(&emitter); 53 | LLVM_Emit(&emitter, ast); 54 | LLVM_Free(&emitter); 55 | } 56 | C_Free(&checker); 57 | 58 | P_Free(&parser); 59 | 60 | free(source); 61 | } 62 | 63 | M_ScratchFree(); 64 | } 65 | -------------------------------------------------------------------------------- /third-party/include/llvm-c/IRReader.h: -------------------------------------------------------------------------------- 1 | /*===-- llvm-c/IRReader.h - IR Reader C Interface -----------------*- C -*-===*\ 2 | |* *| 3 | |* Part of the LLVM Project, under the Apache License v2.0 with LLVM *| 4 | |* Exceptions. *| 5 | |* See https://llvm.org/LICENSE.txt for license information. *| 6 | |* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception *| 7 | |* *| 8 | |*===----------------------------------------------------------------------===*| 9 | |* *| 10 | |* This file defines the C interface to the IR Reader. *| 11 | |* *| 12 | \*===----------------------------------------------------------------------===*/ 13 | 14 | #ifndef LLVM_C_IRREADER_H 15 | #define LLVM_C_IRREADER_H 16 | 17 | #include "llvm-c/ExternC.h" 18 | #include "llvm-c/Types.h" 19 | 20 | LLVM_C_EXTERN_C_BEGIN 21 | 22 | /** 23 | * Read LLVM IR from a memory buffer and convert it into an in-memory Module 24 | * object. Returns 0 on success. 25 | * Optionally returns a human-readable description of any errors that 26 | * occurred during parsing IR. OutMessage must be disposed with 27 | * LLVMDisposeMessage. 28 | * 29 | * @see llvm::ParseIR() 30 | */ 31 | LLVMBool LLVMParseIRInContext(LLVMContextRef ContextRef, 32 | LLVMMemoryBufferRef MemBuf, LLVMModuleRef *OutM, 33 | char **OutMessage); 34 | 35 | LLVM_C_EXTERN_C_END 36 | 37 | #endif 38 | -------------------------------------------------------------------------------- /third-party/include/llvm/Config/Targets.def.in: -------------------------------------------------------------------------------- 1 | /*===- llvm/Config/Targets.def - LLVM Target Architectures ------*- C++ -*-===*\ 2 | |* *| 3 | |* Part of the LLVM Project, under the Apache License v2.0 with LLVM *| 4 | |* Exceptions. *| 5 | |* See https://llvm.org/LICENSE.txt for license information. *| 6 | |* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception *| 7 | |* *| 8 | |*===----------------------------------------------------------------------===*| 9 | |* *| 10 | |* This file enumerates all of the target architectures supported by *| 11 | |* this build of LLVM. Clients of this file should define the *| 12 | |* LLVM_TARGET macro to be a function-like macro with a single *| 13 | |* parameter (the name of the target); including this file will then *| 14 | |* enumerate all of the targets. *| 15 | |* *| 16 | |* The set of targets supported by LLVM is generated at configuration *| 17 | |* time, at which point this header is generated. Do not modify this *| 18 | |* header directly. *| 19 | |* *| 20 | \*===----------------------------------------------------------------------===*/ 21 | 22 | #ifndef LLVM_TARGET 23 | # error Please define the macro LLVM_TARGET(TargetName) 24 | #endif 25 | 26 | @LLVM_ENUM_TARGETS@ 27 | 28 | #undef LLVM_TARGET 29 | -------------------------------------------------------------------------------- /third-party/include/llvm-c/Linker.h: -------------------------------------------------------------------------------- 1 | /*===-- llvm-c/Linker.h - Module Linker C Interface -------------*- C++ -*-===*\ 2 | |* *| 3 | |* Part of the LLVM Project, under the Apache License v2.0 with LLVM *| 4 | |* Exceptions. *| 5 | |* See https://llvm.org/LICENSE.txt for license information. *| 6 | |* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception *| 7 | |* *| 8 | |*===----------------------------------------------------------------------===*| 9 | |* *| 10 | |* This file defines the C interface to the module/file/archive linker. *| 11 | |* *| 12 | \*===----------------------------------------------------------------------===*/ 13 | 14 | #ifndef LLVM_C_LINKER_H 15 | #define LLVM_C_LINKER_H 16 | 17 | #include "llvm-c/ExternC.h" 18 | #include "llvm-c/Types.h" 19 | 20 | LLVM_C_EXTERN_C_BEGIN 21 | 22 | /* This enum is provided for backwards-compatibility only. It has no effect. */ 23 | typedef enum { 24 | LLVMLinkerDestroySource = 0, /* This is the default behavior. */ 25 | LLVMLinkerPreserveSource_Removed = 1 /* This option has been deprecated and 26 | should not be used. */ 27 | } LLVMLinkerMode; 28 | 29 | /* Links the source module into the destination module. The source module is 30 | * destroyed. 31 | * The return value is true if an error occurred, false otherwise. 32 | * Use the diagnostic handler to get any diagnostic message. 33 | */ 34 | LLVMBool LLVMLinkModules2(LLVMModuleRef Dest, LLVMModuleRef Src); 35 | 36 | LLVM_C_EXTERN_C_END 37 | 38 | #endif 39 | -------------------------------------------------------------------------------- /third-party/include/llvm-c/Deprecated.h: -------------------------------------------------------------------------------- 1 | /*===-- llvm-c/Deprecated.h - Deprecation macro -------------------*- C -*-===*\ 2 | |* *| 3 | |* Part of the LLVM Project, under the Apache License v2.0 with LLVM *| 4 | |* Exceptions. *| 5 | |* See https://llvm.org/LICENSE.txt for license information. *| 6 | |* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception *| 7 | |* *| 8 | |*===----------------------------------------------------------------------===*| 9 | |* *| 10 | |* This header declares LLVM_ATTRIBUTE_C_DEPRECATED() macro, which can be *| 11 | |* used to deprecate functions in the C interface. *| 12 | |* *| 13 | \*===----------------------------------------------------------------------===*/ 14 | 15 | #ifndef LLVM_C_DEPRECATED_H 16 | #define LLVM_C_DEPRECATED_H 17 | 18 | #ifndef __has_feature 19 | # define __has_feature(x) 0 20 | #endif 21 | 22 | // This is a variant of LLVM_ATTRIBUTE_DEPRECATED() that is compatible with 23 | // C compilers. 24 | #if __has_feature(attribute_deprecated_with_message) 25 | # define LLVM_ATTRIBUTE_C_DEPRECATED(decl, message) \ 26 | decl __attribute__((deprecated(message))) 27 | #elif defined(__GNUC__) 28 | # define LLVM_ATTRIBUTE_C_DEPRECATED(decl, message) \ 29 | decl __attribute__((deprecated)) 30 | #elif defined(_MSC_VER) 31 | # define LLVM_ATTRIBUTE_C_DEPRECATED(decl, message) \ 32 | __declspec(deprecated(message)) decl 33 | #else 34 | # define LLVM_ATTRIBUTE_C_DEPRECATED(decl, message) \ 35 | decl 36 | #endif 37 | 38 | #endif /* LLVM_C_DEPRECATED_H */ 39 | -------------------------------------------------------------------------------- /third-party/include/llvm/Config/AsmParsers.def.in: -------------------------------------------------------------------------------- 1 | /*===- llvm/Config/AsmParsers.def - LLVM Assembly Parsers -------*- C++ -*-===*\ 2 | |* *| 3 | |* Part of the LLVM Project, under the Apache License v2.0 with LLVM *| 4 | |* Exceptions. *| 5 | |* See https://llvm.org/LICENSE.txt for license information. *| 6 | |* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception *| 7 | |* *| 8 | |*===----------------------------------------------------------------------===*| 9 | |* *| 10 | |* This file enumerates all of the assembly-language parsers *| 11 | |* supported by this build of LLVM. Clients of this file should define *| 12 | |* the LLVM_ASM_PARSER macro to be a function-like macro with a *| 13 | |* single parameter (the name of the target whose assembly can be *| 14 | |* generated); including this file will then enumerate all of the *| 15 | |* targets with assembly parsers. *| 16 | |* *| 17 | |* The set of targets supported by LLVM is generated at configuration *| 18 | |* time, at which point this header is generated. Do not modify this *| 19 | |* header directly. *| 20 | |* *| 21 | \*===----------------------------------------------------------------------===*/ 22 | 23 | #ifndef LLVM_ASM_PARSER 24 | # error Please define the macro LLVM_ASM_PARSER(TargetName) 25 | #endif 26 | 27 | @LLVM_ENUM_ASM_PARSERS@ 28 | 29 | #undef LLVM_ASM_PARSER 30 | -------------------------------------------------------------------------------- /third-party/include/llvm/Config/AsmPrinters.def.in: -------------------------------------------------------------------------------- 1 | /*===- llvm/Config/AsmPrinters.def - LLVM Assembly Printers -----*- C++ -*-===*\ 2 | |* *| 3 | |* Part of the LLVM Project, under the Apache License v2.0 with LLVM *| 4 | |* Exceptions. *| 5 | |* See https://llvm.org/LICENSE.txt for license information. *| 6 | |* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception *| 7 | |* *| 8 | |*===----------------------------------------------------------------------===*| 9 | |* *| 10 | |* This file enumerates all of the assembly-language printers *| 11 | |* supported by this build of LLVM. Clients of this file should define *| 12 | |* the LLVM_ASM_PRINTER macro to be a function-like macro with a *| 13 | |* single parameter (the name of the target whose assembly can be *| 14 | |* generated); including this file will then enumerate all of the *| 15 | |* targets with assembly printers. *| 16 | |* *| 17 | |* The set of targets supported by LLVM is generated at configuration *| 18 | |* time, at which point this header is generated. Do not modify this *| 19 | |* header directly. *| 20 | |* *| 21 | \*===----------------------------------------------------------------------===*/ 22 | 23 | #ifndef LLVM_ASM_PRINTER 24 | # error Please define the macro LLVM_ASM_PRINTER(TargetName) 25 | #endif 26 | 27 | @LLVM_ENUM_ASM_PRINTERS@ 28 | 29 | #undef LLVM_ASM_PRINTER 30 | -------------------------------------------------------------------------------- /third-party/include/llvm/Config/Disassemblers.def.in: -------------------------------------------------------------------------------- 1 | /*===- llvm/Config/Disassemblers.def - LLVM Assembly Parsers ----*- C++ -*-===*\ 2 | |* *| 3 | |* Part of the LLVM Project, under the Apache License v2.0 with LLVM *| 4 | |* Exceptions. *| 5 | |* See https://llvm.org/LICENSE.txt for license information. *| 6 | |* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception *| 7 | |* *| 8 | |*===----------------------------------------------------------------------===*| 9 | |* *| 10 | |* This file enumerates all of the assembly-language parsers *| 11 | |* supported by this build of LLVM. Clients of this file should define *| 12 | |* the LLVM_DISASSEMBLER macro to be a function-like macro with a *| 13 | |* single parameter (the name of the target whose assembly can be *| 14 | |* generated); including this file will then enumerate all of the *| 15 | |* targets with assembly parsers. *| 16 | |* *| 17 | |* The set of targets supported by LLVM is generated at configuration *| 18 | |* time, at which point this header is generated. Do not modify this *| 19 | |* header directly. *| 20 | |* *| 21 | \*===----------------------------------------------------------------------===*/ 22 | 23 | #ifndef LLVM_DISASSEMBLER 24 | # error Please define the macro LLVM_DISASSEMBLER(TargetName) 25 | #endif 26 | 27 | @LLVM_ENUM_DISASSEMBLERS@ 28 | 29 | #undef LLVM_DISASSEMBLER 30 | -------------------------------------------------------------------------------- /third-party/include/llvm-c/ExternC.h: -------------------------------------------------------------------------------- 1 | /*===- llvm-c/ExternC.h - Wrapper for 'extern "C"' ----------------*- C -*-===*\ 2 | |* *| 3 | |* Part of the LLVM Project, under the Apache License v2.0 with LLVM *| 4 | |* Exceptions. *| 5 | |* See https://llvm.org/LICENSE.txt for license information. *| 6 | |* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception *| 7 | |* *| 8 | |*===----------------------------------------------------------------------===*| 9 | |* *| 10 | |* This file defines an 'extern "C"' wrapper *| 11 | |* *| 12 | \*===----------------------------------------------------------------------===*/ 13 | 14 | #ifndef LLVM_C_EXTERNC_H 15 | #define LLVM_C_EXTERNC_H 16 | 17 | #ifdef __clang__ 18 | #define LLVM_C_STRICT_PROTOTYPES_BEGIN \ 19 | _Pragma("clang diagnostic push") \ 20 | _Pragma("clang diagnostic error \"-Wstrict-prototypes\"") 21 | #define LLVM_C_STRICT_PROTOTYPES_END _Pragma("clang diagnostic pop") 22 | #else 23 | #define LLVM_C_STRICT_PROTOTYPES_BEGIN 24 | #define LLVM_C_STRICT_PROTOTYPES_END 25 | #endif 26 | 27 | #ifdef __cplusplus 28 | #define LLVM_C_EXTERN_C_BEGIN \ 29 | extern "C" { \ 30 | LLVM_C_STRICT_PROTOTYPES_BEGIN 31 | #define LLVM_C_EXTERN_C_END \ 32 | LLVM_C_STRICT_PROTOTYPES_END \ 33 | } 34 | #else 35 | #define LLVM_C_EXTERN_C_BEGIN LLVM_C_STRICT_PROTOTYPES_BEGIN 36 | #define LLVM_C_EXTERN_C_END LLVM_C_STRICT_PROTOTYPES_END 37 | #endif 38 | 39 | #endif 40 | -------------------------------------------------------------------------------- /third-party/include/llvm-c/ErrorHandling.h: -------------------------------------------------------------------------------- 1 | /*===-- llvm-c/ErrorHandling.h - Error Handling C Interface -------*- C -*-===*\ 2 | |* *| 3 | |* Part of the LLVM Project, under the Apache License v2.0 with LLVM *| 4 | |* Exceptions. *| 5 | |* See https://llvm.org/LICENSE.txt for license information. *| 6 | |* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception *| 7 | |* *| 8 | |*===----------------------------------------------------------------------===*| 9 | |* *| 10 | |* This file defines the C interface to LLVM's error handling mechanism. *| 11 | |* *| 12 | \*===----------------------------------------------------------------------===*/ 13 | 14 | #ifndef LLVM_C_ERRORHANDLING_H 15 | #define LLVM_C_ERRORHANDLING_H 16 | 17 | #include "llvm-c/ExternC.h" 18 | 19 | LLVM_C_EXTERN_C_BEGIN 20 | 21 | typedef void (*LLVMFatalErrorHandler)(const char *Reason); 22 | 23 | /** 24 | * Install a fatal error handler. By default, if LLVM detects a fatal error, it 25 | * will call exit(1). This may not be appropriate in many contexts. For example, 26 | * doing exit(1) will bypass many crash reporting/tracing system tools. This 27 | * function allows you to install a callback that will be invoked prior to the 28 | * call to exit(1). 29 | */ 30 | void LLVMInstallFatalErrorHandler(LLVMFatalErrorHandler Handler); 31 | 32 | /** 33 | * Reset the fatal error handler. This resets LLVM's fatal error handling 34 | * behavior to the default. 35 | */ 36 | void LLVMResetFatalErrorHandler(void); 37 | 38 | /** 39 | * Enable LLVM's built-in stack trace code. This intercepts the OS's crash 40 | * signals and prints which component of LLVM you were in at the time if the 41 | * crash. 42 | */ 43 | void LLVMEnablePrettyStackTrace(void); 44 | 45 | LLVM_C_EXTERN_C_END 46 | 47 | #endif 48 | -------------------------------------------------------------------------------- /third-party/include/llvm-c/Transforms/Vectorize.h: -------------------------------------------------------------------------------- 1 | /*===---------------------------Vectorize.h --------------------- -*- C -*-===*\ 2 | |*===----------- Vectorization Transformation Library C Interface ---------===*| 3 | |* *| 4 | |* Part of the LLVM Project, under the Apache License v2.0 with LLVM *| 5 | |* Exceptions. *| 6 | |* See https://llvm.org/LICENSE.txt for license information. *| 7 | |* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception *| 8 | |* *| 9 | |*===----------------------------------------------------------------------===*| 10 | |* *| 11 | |* This header declares the C interface to libLLVMVectorize.a, which *| 12 | |* implements various vectorization transformations of the LLVM IR. *| 13 | |* *| 14 | |* Many exotic languages can interoperate with C code but have a harder time *| 15 | |* with C++ due to name mangling. So in addition to C, this interface enables *| 16 | |* tools written in such languages. *| 17 | |* *| 18 | \*===----------------------------------------------------------------------===*/ 19 | 20 | #ifndef LLVM_C_TRANSFORMS_VECTORIZE_H 21 | #define LLVM_C_TRANSFORMS_VECTORIZE_H 22 | 23 | #include "llvm-c/ExternC.h" 24 | #include "llvm-c/Types.h" 25 | 26 | LLVM_C_EXTERN_C_BEGIN 27 | 28 | /** 29 | * @defgroup LLVMCTransformsVectorize Vectorization transformations 30 | * @ingroup LLVMCTransforms 31 | * 32 | * @{ 33 | */ 34 | 35 | /** See llvm::createLoopVectorizePass function. */ 36 | void LLVMAddLoopVectorizePass(LLVMPassManagerRef PM); 37 | 38 | /** See llvm::createSLPVectorizerPass function. */ 39 | void LLVMAddSLPVectorizePass(LLVMPassManagerRef PM); 40 | 41 | /** 42 | * @} 43 | */ 44 | 45 | LLVM_C_EXTERN_C_END 46 | 47 | #endif 48 | -------------------------------------------------------------------------------- /third-party/include/llvm-c/Transforms/Utils.h: -------------------------------------------------------------------------------- 1 | /*===-- Utils.h - Transformation Utils Library C Interface ------*- C++ -*-===*\ 2 | |* *| 3 | |* Part of the LLVM Project, under the Apache License v2.0 with LLVM *| 4 | |* Exceptions. *| 5 | |* See https://llvm.org/LICENSE.txt for license information. *| 6 | |* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception *| 7 | |* *| 8 | |*===----------------------------------------------------------------------===*| 9 | |* *| 10 | |* This header declares the C interface to libLLVMTransformUtils.a, which *| 11 | |* implements various transformation utilities of the LLVM IR. *| 12 | |* *| 13 | |* Many exotic languages can interoperate with C code but have a harder time *| 14 | |* with C++ due to name mangling. So in addition to C, this interface enables *| 15 | |* tools written in such languages. *| 16 | |* *| 17 | \*===----------------------------------------------------------------------===*/ 18 | 19 | #ifndef LLVM_C_TRANSFORMS_UTILS_H 20 | #define LLVM_C_TRANSFORMS_UTILS_H 21 | 22 | #include "llvm-c/ExternC.h" 23 | #include "llvm-c/Types.h" 24 | 25 | LLVM_C_EXTERN_C_BEGIN 26 | 27 | /** 28 | * @defgroup LLVMCTransformsUtils Transformation Utilities 29 | * @ingroup LLVMCTransforms 30 | * 31 | * @{ 32 | */ 33 | 34 | /** See llvm::createLowerSwitchPass function. */ 35 | void LLVMAddLowerSwitchPass(LLVMPassManagerRef PM); 36 | 37 | /** See llvm::createPromoteMemoryToRegisterPass function. */ 38 | void LLVMAddPromoteMemoryToRegisterPass(LLVMPassManagerRef PM); 39 | 40 | /** See llvm::createAddDiscriminatorsPass function. */ 41 | void LLVMAddAddDiscriminatorsPass(LLVMPassManagerRef PM); 42 | 43 | /** 44 | * @} 45 | */ 46 | 47 | LLVM_C_EXTERN_C_END 48 | 49 | #endif 50 | 51 | -------------------------------------------------------------------------------- /third-party/include/llvm/Config/Targets.def: -------------------------------------------------------------------------------- 1 | /*===- llvm/Config/Targets.def - LLVM Target Architectures ------*- C++ -*-===*\ 2 | |* *| 3 | |* Part of the LLVM Project, under the Apache License v2.0 with LLVM *| 4 | |* Exceptions. *| 5 | |* See https://llvm.org/LICENSE.txt for license information. *| 6 | |* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception *| 7 | |* *| 8 | |*===----------------------------------------------------------------------===*| 9 | |* *| 10 | |* This file enumerates all of the target architectures supported by *| 11 | |* this build of LLVM. Clients of this file should define the *| 12 | |* LLVM_TARGET macro to be a function-like macro with a single *| 13 | |* parameter (the name of the target); including this file will then *| 14 | |* enumerate all of the targets. *| 15 | |* *| 16 | |* The set of targets supported by LLVM is generated at configuration *| 17 | |* time, at which point this header is generated. Do not modify this *| 18 | |* header directly. *| 19 | |* *| 20 | \*===----------------------------------------------------------------------===*/ 21 | 22 | #ifndef LLVM_TARGET 23 | # error Please define the macro LLVM_TARGET(TargetName) 24 | #endif 25 | 26 | LLVM_TARGET(AArch64) 27 | LLVM_TARGET(AMDGPU) 28 | LLVM_TARGET(ARM) 29 | LLVM_TARGET(AVR) 30 | LLVM_TARGET(BPF) 31 | LLVM_TARGET(Hexagon) 32 | LLVM_TARGET(Lanai) 33 | LLVM_TARGET(Mips) 34 | LLVM_TARGET(MSP430) 35 | LLVM_TARGET(NVPTX) 36 | LLVM_TARGET(PowerPC) 37 | LLVM_TARGET(RISCV) 38 | LLVM_TARGET(Sparc) 39 | LLVM_TARGET(SystemZ) 40 | LLVM_TARGET(WebAssembly) 41 | LLVM_TARGET(X86) 42 | LLVM_TARGET(XCore) 43 | 44 | 45 | #undef LLVM_TARGET 46 | -------------------------------------------------------------------------------- /third-party/include/llvm/Config/AsmParsers.def: -------------------------------------------------------------------------------- 1 | /*===- llvm/Config/AsmParsers.def - LLVM Assembly Parsers -------*- C++ -*-===*\ 2 | |* *| 3 | |* Part of the LLVM Project, under the Apache License v2.0 with LLVM *| 4 | |* Exceptions. *| 5 | |* See https://llvm.org/LICENSE.txt for license information. *| 6 | |* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception *| 7 | |* *| 8 | |*===----------------------------------------------------------------------===*| 9 | |* *| 10 | |* This file enumerates all of the assembly-language parsers *| 11 | |* supported by this build of LLVM. Clients of this file should define *| 12 | |* the LLVM_ASM_PARSER macro to be a function-like macro with a *| 13 | |* single parameter (the name of the target whose assembly can be *| 14 | |* generated); including this file will then enumerate all of the *| 15 | |* targets with assembly parsers. *| 16 | |* *| 17 | |* The set of targets supported by LLVM is generated at configuration *| 18 | |* time, at which point this header is generated. Do not modify this *| 19 | |* header directly. *| 20 | |* *| 21 | \*===----------------------------------------------------------------------===*/ 22 | 23 | #ifndef LLVM_ASM_PARSER 24 | # error Please define the macro LLVM_ASM_PARSER(TargetName) 25 | #endif 26 | 27 | LLVM_ASM_PARSER(AArch64) 28 | LLVM_ASM_PARSER(AMDGPU) 29 | LLVM_ASM_PARSER(ARM) 30 | LLVM_ASM_PARSER(AVR) 31 | LLVM_ASM_PARSER(BPF) 32 | LLVM_ASM_PARSER(Hexagon) 33 | LLVM_ASM_PARSER(Lanai) 34 | LLVM_ASM_PARSER(Mips) 35 | LLVM_ASM_PARSER(MSP430) 36 | LLVM_ASM_PARSER(PowerPC) 37 | LLVM_ASM_PARSER(RISCV) 38 | LLVM_ASM_PARSER(Sparc) 39 | LLVM_ASM_PARSER(SystemZ) 40 | LLVM_ASM_PARSER(WebAssembly) 41 | LLVM_ASM_PARSER(X86) 42 | 43 | 44 | #undef LLVM_ASM_PARSER 45 | -------------------------------------------------------------------------------- /third-party/include/llvm-c/Initialization.h: -------------------------------------------------------------------------------- 1 | /*===-- llvm-c/Initialization.h - Initialization C Interface ------*- C -*-===*\ 2 | |* *| 3 | |* Part of the LLVM Project, under the Apache License v2.0 with LLVM *| 4 | |* Exceptions. *| 5 | |* See https://llvm.org/LICENSE.txt for license information. *| 6 | |* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception *| 7 | |* *| 8 | |*===----------------------------------------------------------------------===*| 9 | |* *| 10 | |* This header declares the C interface to LLVM initialization routines, *| 11 | |* which must be called before you can use the functionality provided by *| 12 | |* the corresponding LLVM library. *| 13 | |* *| 14 | \*===----------------------------------------------------------------------===*/ 15 | 16 | #ifndef LLVM_C_INITIALIZATION_H 17 | #define LLVM_C_INITIALIZATION_H 18 | 19 | #include "llvm-c/ExternC.h" 20 | #include "llvm-c/Types.h" 21 | 22 | LLVM_C_EXTERN_C_BEGIN 23 | 24 | /** 25 | * @defgroup LLVMCInitialization Initialization Routines 26 | * @ingroup LLVMC 27 | * 28 | * This module contains routines used to initialize the LLVM system. 29 | * 30 | * @{ 31 | */ 32 | 33 | void LLVMInitializeCore(LLVMPassRegistryRef R); 34 | void LLVMInitializeTransformUtils(LLVMPassRegistryRef R); 35 | void LLVMInitializeScalarOpts(LLVMPassRegistryRef R); 36 | void LLVMInitializeObjCARCOpts(LLVMPassRegistryRef R); 37 | void LLVMInitializeVectorization(LLVMPassRegistryRef R); 38 | void LLVMInitializeInstCombine(LLVMPassRegistryRef R); 39 | void LLVMInitializeAggressiveInstCombiner(LLVMPassRegistryRef R); 40 | void LLVMInitializeIPO(LLVMPassRegistryRef R); 41 | void LLVMInitializeInstrumentation(LLVMPassRegistryRef R); 42 | void LLVMInitializeAnalysis(LLVMPassRegistryRef R); 43 | void LLVMInitializeIPA(LLVMPassRegistryRef R); 44 | void LLVMInitializeCodeGen(LLVMPassRegistryRef R); 45 | void LLVMInitializeTarget(LLVMPassRegistryRef R); 46 | 47 | /** 48 | * @} 49 | */ 50 | 51 | LLVM_C_EXTERN_C_END 52 | 53 | #endif 54 | -------------------------------------------------------------------------------- /third-party/include/llvm/Config/Disassemblers.def: -------------------------------------------------------------------------------- 1 | /*===- llvm/Config/Disassemblers.def - LLVM Assembly Parsers ----*- C++ -*-===*\ 2 | |* *| 3 | |* Part of the LLVM Project, under the Apache License v2.0 with LLVM *| 4 | |* Exceptions. *| 5 | |* See https://llvm.org/LICENSE.txt for license information. *| 6 | |* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception *| 7 | |* *| 8 | |*===----------------------------------------------------------------------===*| 9 | |* *| 10 | |* This file enumerates all of the assembly-language parsers *| 11 | |* supported by this build of LLVM. Clients of this file should define *| 12 | |* the LLVM_DISASSEMBLER macro to be a function-like macro with a *| 13 | |* single parameter (the name of the target whose assembly can be *| 14 | |* generated); including this file will then enumerate all of the *| 15 | |* targets with assembly parsers. *| 16 | |* *| 17 | |* The set of targets supported by LLVM is generated at configuration *| 18 | |* time, at which point this header is generated. Do not modify this *| 19 | |* header directly. *| 20 | |* *| 21 | \*===----------------------------------------------------------------------===*/ 22 | 23 | #ifndef LLVM_DISASSEMBLER 24 | # error Please define the macro LLVM_DISASSEMBLER(TargetName) 25 | #endif 26 | 27 | LLVM_DISASSEMBLER(AArch64) 28 | LLVM_DISASSEMBLER(AMDGPU) 29 | LLVM_DISASSEMBLER(ARM) 30 | LLVM_DISASSEMBLER(AVR) 31 | LLVM_DISASSEMBLER(BPF) 32 | LLVM_DISASSEMBLER(Hexagon) 33 | LLVM_DISASSEMBLER(Lanai) 34 | LLVM_DISASSEMBLER(Mips) 35 | LLVM_DISASSEMBLER(MSP430) 36 | LLVM_DISASSEMBLER(PowerPC) 37 | LLVM_DISASSEMBLER(RISCV) 38 | LLVM_DISASSEMBLER(Sparc) 39 | LLVM_DISASSEMBLER(SystemZ) 40 | LLVM_DISASSEMBLER(WebAssembly) 41 | LLVM_DISASSEMBLER(X86) 42 | LLVM_DISASSEMBLER(XCore) 43 | 44 | 45 | #undef LLVM_DISASSEMBLER 46 | -------------------------------------------------------------------------------- /third-party/include/llvm/Config/AsmPrinters.def: -------------------------------------------------------------------------------- 1 | /*===- llvm/Config/AsmPrinters.def - LLVM Assembly Printers -----*- C++ -*-===*\ 2 | |* *| 3 | |* Part of the LLVM Project, under the Apache License v2.0 with LLVM *| 4 | |* Exceptions. *| 5 | |* See https://llvm.org/LICENSE.txt for license information. *| 6 | |* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception *| 7 | |* *| 8 | |*===----------------------------------------------------------------------===*| 9 | |* *| 10 | |* This file enumerates all of the assembly-language printers *| 11 | |* supported by this build of LLVM. Clients of this file should define *| 12 | |* the LLVM_ASM_PRINTER macro to be a function-like macro with a *| 13 | |* single parameter (the name of the target whose assembly can be *| 14 | |* generated); including this file will then enumerate all of the *| 15 | |* targets with assembly printers. *| 16 | |* *| 17 | |* The set of targets supported by LLVM is generated at configuration *| 18 | |* time, at which point this header is generated. Do not modify this *| 19 | |* header directly. *| 20 | |* *| 21 | \*===----------------------------------------------------------------------===*/ 22 | 23 | #ifndef LLVM_ASM_PRINTER 24 | # error Please define the macro LLVM_ASM_PRINTER(TargetName) 25 | #endif 26 | 27 | LLVM_ASM_PRINTER(AArch64) 28 | LLVM_ASM_PRINTER(AMDGPU) 29 | LLVM_ASM_PRINTER(ARM) 30 | LLVM_ASM_PRINTER(AVR) 31 | LLVM_ASM_PRINTER(BPF) 32 | LLVM_ASM_PRINTER(Hexagon) 33 | LLVM_ASM_PRINTER(Lanai) 34 | LLVM_ASM_PRINTER(Mips) 35 | LLVM_ASM_PRINTER(MSP430) 36 | LLVM_ASM_PRINTER(NVPTX) 37 | LLVM_ASM_PRINTER(PowerPC) 38 | LLVM_ASM_PRINTER(RISCV) 39 | LLVM_ASM_PRINTER(Sparc) 40 | LLVM_ASM_PRINTER(SystemZ) 41 | LLVM_ASM_PRINTER(WebAssembly) 42 | LLVM_ASM_PRINTER(X86) 43 | LLVM_ASM_PRINTER(XCore) 44 | 45 | 46 | #undef LLVM_ASM_PRINTER 47 | -------------------------------------------------------------------------------- /third-party/include/llvm-c/Transforms/Coroutines.h: -------------------------------------------------------------------------------- 1 | /*===-- Coroutines.h - Coroutines Library C Interface -----------*- C++ -*-===*\ 2 | |* *| 3 | |* Part of the LLVM Project, under the Apache License v2.0 with LLVM *| 4 | |* Exceptions. *| 5 | |* See https://llvm.org/LICENSE.txt for license information. *| 6 | |* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception *| 7 | |* *| 8 | |*===----------------------------------------------------------------------===*| 9 | |* *| 10 | |* This header declares the C interface to libLLVMCoroutines.a, which *| 11 | |* implements various scalar transformations of the LLVM IR. *| 12 | |* *| 13 | |* Many exotic languages can interoperate with C code but have a harder time *| 14 | |* with C++ due to name mangling. So in addition to C, this interface enables *| 15 | |* tools written in such languages. *| 16 | |* *| 17 | \*===----------------------------------------------------------------------===*/ 18 | 19 | #ifndef LLVM_C_TRANSFORMS_COROUTINES_H 20 | #define LLVM_C_TRANSFORMS_COROUTINES_H 21 | 22 | #include "llvm-c/ExternC.h" 23 | #include "llvm-c/Types.h" 24 | #include "llvm-c/Transforms/PassManagerBuilder.h" 25 | 26 | LLVM_C_EXTERN_C_BEGIN 27 | 28 | /** 29 | * @defgroup LLVMCTransformsCoroutines Coroutine transformations 30 | * @ingroup LLVMCTransforms 31 | * 32 | * @{ 33 | */ 34 | 35 | /** See llvm::createCoroEarlyLegacyPass function. */ 36 | void LLVMAddCoroEarlyPass(LLVMPassManagerRef PM); 37 | 38 | /** See llvm::createCoroSplitLegacyPass function. */ 39 | void LLVMAddCoroSplitPass(LLVMPassManagerRef PM); 40 | 41 | /** See llvm::createCoroElideLegacyPass function. */ 42 | void LLVMAddCoroElidePass(LLVMPassManagerRef PM); 43 | 44 | /** See llvm::createCoroCleanupLegacyPass function. */ 45 | void LLVMAddCoroCleanupPass(LLVMPassManagerRef PM); 46 | 47 | /** See llvm::addCoroutinePassesToExtensionPoints. */ 48 | void LLVMPassManagerBuilderAddCoroutinePassesToExtensionPoints(LLVMPassManagerBuilderRef PMB); 49 | 50 | /** 51 | * @} 52 | */ 53 | 54 | LLVM_C_EXTERN_C_END 55 | 56 | #endif 57 | -------------------------------------------------------------------------------- /third-party/include/llvm-c/BitWriter.h: -------------------------------------------------------------------------------- 1 | /*===-- llvm-c/BitWriter.h - BitWriter Library C Interface ------*- C++ -*-===*\ 2 | |* *| 3 | |* Part of the LLVM Project, under the Apache License v2.0 with LLVM *| 4 | |* Exceptions. *| 5 | |* See https://llvm.org/LICENSE.txt for license information. *| 6 | |* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception *| 7 | |* *| 8 | |*===----------------------------------------------------------------------===*| 9 | |* *| 10 | |* This header declares the C interface to libLLVMBitWriter.a, which *| 11 | |* implements output of the LLVM bitcode format. *| 12 | |* *| 13 | |* Many exotic languages can interoperate with C code but have a harder time *| 14 | |* with C++ due to name mangling. So in addition to C, this interface enables *| 15 | |* tools written in such languages. *| 16 | |* *| 17 | \*===----------------------------------------------------------------------===*/ 18 | 19 | #ifndef LLVM_C_BITWRITER_H 20 | #define LLVM_C_BITWRITER_H 21 | 22 | #include "llvm-c/ExternC.h" 23 | #include "llvm-c/Types.h" 24 | 25 | LLVM_C_EXTERN_C_BEGIN 26 | 27 | /** 28 | * @defgroup LLVMCBitWriter Bit Writer 29 | * @ingroup LLVMC 30 | * 31 | * @{ 32 | */ 33 | 34 | /*===-- Operations on modules ---------------------------------------------===*/ 35 | 36 | /** Writes a module to the specified path. Returns 0 on success. */ 37 | int LLVMWriteBitcodeToFile(LLVMModuleRef M, const char *Path); 38 | 39 | /** Writes a module to an open file descriptor. Returns 0 on success. */ 40 | int LLVMWriteBitcodeToFD(LLVMModuleRef M, int FD, int ShouldClose, 41 | int Unbuffered); 42 | 43 | /** Deprecated for LLVMWriteBitcodeToFD. Writes a module to an open file 44 | descriptor. Returns 0 on success. Closes the Handle. */ 45 | int LLVMWriteBitcodeToFileHandle(LLVMModuleRef M, int Handle); 46 | 47 | /** Writes a module to a new memory buffer and returns it. */ 48 | LLVMMemoryBufferRef LLVMWriteBitcodeToMemoryBuffer(LLVMModuleRef M); 49 | 50 | /** 51 | * @} 52 | */ 53 | 54 | LLVM_C_EXTERN_C_END 55 | 56 | #endif 57 | -------------------------------------------------------------------------------- /third-party/include/llvm-c/Support.h: -------------------------------------------------------------------------------- 1 | /*===-- llvm-c/Support.h - Support C Interface --------------------*- C -*-===*\ 2 | |* *| 3 | |* Part of the LLVM Project, under the Apache License v2.0 with LLVM *| 4 | |* Exceptions. *| 5 | |* See https://llvm.org/LICENSE.txt for license information. *| 6 | |* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception *| 7 | |* *| 8 | |*===----------------------------------------------------------------------===*| 9 | |* *| 10 | |* This file defines the C interface to the LLVM support library. *| 11 | |* *| 12 | \*===----------------------------------------------------------------------===*/ 13 | 14 | #ifndef LLVM_C_SUPPORT_H 15 | #define LLVM_C_SUPPORT_H 16 | 17 | #include "llvm-c/DataTypes.h" 18 | #include "llvm-c/ExternC.h" 19 | #include "llvm-c/Types.h" 20 | 21 | LLVM_C_EXTERN_C_BEGIN 22 | 23 | /** 24 | * This function permanently loads the dynamic library at the given path. 25 | * It is safe to call this function multiple times for the same library. 26 | * 27 | * @see sys::DynamicLibrary::LoadLibraryPermanently() 28 | */ 29 | LLVMBool LLVMLoadLibraryPermanently(const char* Filename); 30 | 31 | /** 32 | * This function parses the given arguments using the LLVM command line parser. 33 | * Note that the only stable thing about this function is its signature; you 34 | * cannot rely on any particular set of command line arguments being interpreted 35 | * the same way across LLVM versions. 36 | * 37 | * @see llvm::cl::ParseCommandLineOptions() 38 | */ 39 | void LLVMParseCommandLineOptions(int argc, const char *const *argv, 40 | const char *Overview); 41 | 42 | /** 43 | * This function will search through all previously loaded dynamic 44 | * libraries for the symbol \p symbolName. If it is found, the address of 45 | * that symbol is returned. If not, null is returned. 46 | * 47 | * @see sys::DynamicLibrary::SearchForAddressOfSymbol() 48 | */ 49 | void *LLVMSearchForAddressOfSymbol(const char *symbolName); 50 | 51 | /** 52 | * This functions permanently adds the symbol \p symbolName with the 53 | * value \p symbolValue. These symbols are searched before any 54 | * libraries. 55 | * 56 | * @see sys::DynamicLibrary::AddSymbol() 57 | */ 58 | void LLVMAddSymbol(const char *symbolName, void *symbolValue); 59 | 60 | LLVM_C_EXTERN_C_END 61 | 62 | #endif 63 | -------------------------------------------------------------------------------- /third-party/include/llvm-c/Error.h: -------------------------------------------------------------------------------- 1 | /*===------- llvm-c/Error.h - llvm::Error class C Interface -------*- C -*-===*\ 2 | |* *| 3 | |* Part of the LLVM Project, under the Apache License v2.0 with LLVM *| 4 | |* Exceptions. *| 5 | |* See https://llvm.org/LICENSE.txt for license information. *| 6 | |* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception *| 7 | |* *| 8 | |*===----------------------------------------------------------------------===*| 9 | |* *| 10 | |* This file defines the C interface to LLVM's Error class. *| 11 | |* *| 12 | \*===----------------------------------------------------------------------===*/ 13 | 14 | #ifndef LLVM_C_ERROR_H 15 | #define LLVM_C_ERROR_H 16 | 17 | #include "llvm-c/ExternC.h" 18 | 19 | LLVM_C_EXTERN_C_BEGIN 20 | 21 | #define LLVMErrorSuccess 0 22 | 23 | /** 24 | * Opaque reference to an error instance. Null serves as the 'success' value. 25 | */ 26 | typedef struct LLVMOpaqueError *LLVMErrorRef; 27 | 28 | /** 29 | * Error type identifier. 30 | */ 31 | typedef const void *LLVMErrorTypeId; 32 | 33 | /** 34 | * Returns the type id for the given error instance, which must be a failure 35 | * value (i.e. non-null). 36 | */ 37 | LLVMErrorTypeId LLVMGetErrorTypeId(LLVMErrorRef Err); 38 | 39 | /** 40 | * Dispose of the given error without handling it. This operation consumes the 41 | * error, and the given LLVMErrorRef value is not usable once this call returns. 42 | * Note: This method *only* needs to be called if the error is not being passed 43 | * to some other consuming operation, e.g. LLVMGetErrorMessage. 44 | */ 45 | void LLVMConsumeError(LLVMErrorRef Err); 46 | 47 | /** 48 | * Returns the given string's error message. This operation consumes the error, 49 | * and the given LLVMErrorRef value is not usable once this call returns. 50 | * The caller is responsible for disposing of the string by calling 51 | * LLVMDisposeErrorMessage. 52 | */ 53 | char *LLVMGetErrorMessage(LLVMErrorRef Err); 54 | 55 | /** 56 | * Dispose of the given error message. 57 | */ 58 | void LLVMDisposeErrorMessage(char *ErrMsg); 59 | 60 | /** 61 | * Returns the type id for llvm StringError. 62 | */ 63 | LLVMErrorTypeId LLVMGetStringErrorTypeId(void); 64 | 65 | /** 66 | * Create a StringError. 67 | */ 68 | LLVMErrorRef LLVMCreateStringError(const char *ErrMsg); 69 | 70 | LLVM_C_EXTERN_C_END 71 | 72 | #endif 73 | -------------------------------------------------------------------------------- /third-party/include/llvm/Config/abi-breaking.h: -------------------------------------------------------------------------------- 1 | /*===------- llvm/Config/abi-breaking.h - llvm configuration -------*- C -*-===*/ 2 | /* */ 3 | /* Part of the LLVM Project, under the Apache License v2.0 with LLVM */ 4 | /* Exceptions. */ 5 | /* See https://llvm.org/LICENSE.txt for license information. */ 6 | /* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception */ 7 | /* */ 8 | /*===----------------------------------------------------------------------===*/ 9 | 10 | /* This file controls the C++ ABI break introduced in LLVM public header. */ 11 | 12 | #ifndef LLVM_ABI_BREAKING_CHECKS_H 13 | #define LLVM_ABI_BREAKING_CHECKS_H 14 | 15 | /* Define to enable checks that alter the LLVM C++ ABI */ 16 | #define LLVM_ENABLE_ABI_BREAKING_CHECKS 0 17 | 18 | /* Define to enable reverse iteration of unordered llvm containers */ 19 | #define LLVM_ENABLE_REVERSE_ITERATION 0 20 | 21 | /* Allow selectively disabling link-time mismatch checking so that header-only 22 | ADT content from LLVM can be used without linking libSupport. */ 23 | #if !defined(LLVM_DISABLE_ABI_BREAKING_CHECKS_ENFORCING) || !LLVM_DISABLE_ABI_BREAKING_CHECKS_ENFORCING 24 | 25 | // ABI_BREAKING_CHECKS protection: provides link-time failure when clients build 26 | // mismatch with LLVM 27 | #if defined(_MSC_VER) 28 | // Use pragma with MSVC 29 | #define LLVM_XSTR(s) LLVM_STR(s) 30 | #define LLVM_STR(s) #s 31 | #pragma detect_mismatch("LLVM_ENABLE_ABI_BREAKING_CHECKS", LLVM_XSTR(LLVM_ENABLE_ABI_BREAKING_CHECKS)) 32 | #undef LLVM_XSTR 33 | #undef LLVM_STR 34 | #elif defined(_WIN32) || defined(__CYGWIN__) // Win32 w/o #pragma detect_mismatch 35 | // FIXME: Implement checks without weak. 36 | #elif defined(__cplusplus) 37 | #if !(defined(_AIX) && defined(__GNUC__) && !defined(__clang__)) 38 | #define LLVM_HIDDEN_VISIBILITY __attribute__ ((visibility("hidden"))) 39 | #else 40 | // GCC on AIX does not support visibility attributes. Symbols are not 41 | // exported by default on AIX. 42 | #define LLVM_HIDDEN_VISIBILITY 43 | #endif 44 | namespace llvm { 45 | #if LLVM_ENABLE_ABI_BREAKING_CHECKS 46 | extern int EnableABIBreakingChecks; 47 | LLVM_HIDDEN_VISIBILITY 48 | __attribute__((weak)) int *VerifyEnableABIBreakingChecks = 49 | &EnableABIBreakingChecks; 50 | #else 51 | extern int DisableABIBreakingChecks; 52 | LLVM_HIDDEN_VISIBILITY 53 | __attribute__((weak)) int *VerifyDisableABIBreakingChecks = 54 | &DisableABIBreakingChecks; 55 | #endif 56 | } 57 | #undef LLVM_HIDDEN_VISIBILITY 58 | #endif // _MSC_VER 59 | 60 | #endif // LLVM_DISABLE_ABI_BREAKING_CHECKS_ENFORCING 61 | 62 | #endif 63 | -------------------------------------------------------------------------------- /source/base/str.h: -------------------------------------------------------------------------------- 1 | /* date = September 27th 2021 3:04 pm */ 2 | 3 | #ifndef STR_H 4 | #define STR_H 5 | 6 | #include 7 | #include "mem.h" 8 | 9 | typedef struct string_const { 10 | u8* str; 11 | u64 size; 12 | } string_const; 13 | typedef string_const string; 14 | 15 | typedef struct string_const_list_node { 16 | string str; 17 | struct string_const_list_node* next; 18 | } string_const_list_node; 19 | typedef string_const_list_node string_list_node; 20 | 21 | typedef struct string_const_list { 22 | string_const_list_node* first; 23 | string_const_list_node* last; 24 | i32 node_count; 25 | u64 total_size; 26 | } string_const_list; 27 | typedef string_const_list string_list; 28 | 29 | typedef struct string_const_array { 30 | u32 cap; 31 | u32 len; 32 | string* elems; 33 | } string_const_array; 34 | typedef string_const_array string_array; 35 | 36 | void string_array_add(string_const_array* array, string data); 37 | string_const string_array_remove(string_const_array* array, int idx); 38 | void string_array_free(string_const_array* array); 39 | 40 | //- 41 | 42 | #define str_lit(s) (string_const) { .str = (u8*)(s), .size = sizeof(s) - 1 } 43 | #define str_expand(s) (i32)(s).size, (s).str 44 | 45 | string_const str_alloc(M_Arena* arena, u64 size); // NOTE(EVERYONE): this will try to get one extra byte for \0 46 | string_const str_copy(M_Arena* arena, string_const other); 47 | string_const str_cat(M_Arena* arena, string_const a, string_const b); 48 | string_const str_from_format(M_Arena* arena, const char* format, ...); 49 | string_const str_replace_all(M_Arena* arena, string_const to_fix, string_const needle, string_const replacement); 50 | u64 str_substr_count(string_const str, string_const needle); 51 | u64 str_find_first(string_const str, string_const needle, u32 offset); 52 | u64 str_find_last(string_const str, string_const needle, u32 offset); 53 | u32 str_hash(string_const str); 54 | 55 | b8 str_eq(string_const a, string_const b); 56 | 57 | void string_list_push_node(string_const_list* list, string_const_list_node* node); 58 | void string_list_push(M_Arena* arena, string_const_list* list, string_const str); 59 | b8 string_list_equals(string_const_list* a, string_const_list* b); 60 | b8 string_list_contains(string_const_list* a, string_const needle); 61 | string_const string_list_flatten(M_Arena* arena, string_const_list* list); 62 | 63 | //- Encoding Stuff 64 | 65 | typedef struct string_utf16_const { 66 | u16* str; 67 | u64 size; 68 | } string_utf16_const; 69 | typedef string_utf16_const string_utf16; 70 | 71 | string_utf16_const str16_cstring(u16 *cstr); 72 | string_utf16_const str16_from_str8(M_Arena *arena, string_const str); 73 | string_const str8_from_str16(M_Arena *arena, string_utf16_const str); 74 | 75 | #endif //STR_H 76 | -------------------------------------------------------------------------------- /third-party/include/llvm/Config/abi-breaking.h.cmake: -------------------------------------------------------------------------------- 1 | /*===------- llvm/Config/abi-breaking.h - llvm configuration -------*- C -*-===*/ 2 | /* */ 3 | /* Part of the LLVM Project, under the Apache License v2.0 with LLVM */ 4 | /* Exceptions. */ 5 | /* See https://llvm.org/LICENSE.txt for license information. */ 6 | /* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception */ 7 | /* */ 8 | /*===----------------------------------------------------------------------===*/ 9 | 10 | /* This file controls the C++ ABI break introduced in LLVM public header. */ 11 | 12 | #ifndef LLVM_ABI_BREAKING_CHECKS_H 13 | #define LLVM_ABI_BREAKING_CHECKS_H 14 | 15 | /* Define to enable checks that alter the LLVM C++ ABI */ 16 | #cmakedefine01 LLVM_ENABLE_ABI_BREAKING_CHECKS 17 | 18 | /* Define to enable reverse iteration of unordered llvm containers */ 19 | #cmakedefine01 LLVM_ENABLE_REVERSE_ITERATION 20 | 21 | /* Allow selectively disabling link-time mismatch checking so that header-only 22 | ADT content from LLVM can be used without linking libSupport. */ 23 | #if !defined(LLVM_DISABLE_ABI_BREAKING_CHECKS_ENFORCING) || !LLVM_DISABLE_ABI_BREAKING_CHECKS_ENFORCING 24 | 25 | // ABI_BREAKING_CHECKS protection: provides link-time failure when clients build 26 | // mismatch with LLVM 27 | #if defined(_MSC_VER) 28 | // Use pragma with MSVC 29 | #define LLVM_XSTR(s) LLVM_STR(s) 30 | #define LLVM_STR(s) #s 31 | #pragma detect_mismatch("LLVM_ENABLE_ABI_BREAKING_CHECKS", LLVM_XSTR(LLVM_ENABLE_ABI_BREAKING_CHECKS)) 32 | #undef LLVM_XSTR 33 | #undef LLVM_STR 34 | #elif defined(_WIN32) || defined(__CYGWIN__) // Win32 w/o #pragma detect_mismatch 35 | // FIXME: Implement checks without weak. 36 | #elif defined(__cplusplus) 37 | #if !(defined(_AIX) && defined(__GNUC__) && !defined(__clang__)) 38 | #define LLVM_HIDDEN_VISIBILITY __attribute__ ((visibility("hidden"))) 39 | #else 40 | // GCC on AIX does not support visibility attributes. Symbols are not 41 | // exported by default on AIX. 42 | #define LLVM_HIDDEN_VISIBILITY 43 | #endif 44 | namespace llvm { 45 | #if LLVM_ENABLE_ABI_BREAKING_CHECKS 46 | extern int EnableABIBreakingChecks; 47 | LLVM_HIDDEN_VISIBILITY 48 | __attribute__((weak)) int *VerifyEnableABIBreakingChecks = 49 | &EnableABIBreakingChecks; 50 | #else 51 | extern int DisableABIBreakingChecks; 52 | LLVM_HIDDEN_VISIBILITY 53 | __attribute__((weak)) int *VerifyDisableABIBreakingChecks = 54 | &DisableABIBreakingChecks; 55 | #endif 56 | } 57 | #undef LLVM_HIDDEN_VISIBILITY 58 | #endif // _MSC_VER 59 | 60 | #endif // LLVM_DISABLE_ABI_BREAKING_CHECKS_ENFORCING 61 | 62 | #endif 63 | -------------------------------------------------------------------------------- /third-party/include/llvm-c/OrcEE.h: -------------------------------------------------------------------------------- 1 | /*===-- llvm-c/OrcEE.h - OrcV2 C bindings ExecutionEngine utils -*- C++ -*-===*\ 2 | |* *| 3 | |* Part of the LLVM Project, under the Apache License v2.0 with LLVM *| 4 | |* Exceptions. *| 5 | |* See https://llvm.org/LICENSE.txt for license information. *| 6 | |* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception *| 7 | |* *| 8 | |*===----------------------------------------------------------------------===*| 9 | |* *| 10 | |* This header declares the C interface to ExecutionEngine based utils, e.g. *| 11 | |* RTDyldObjectLinkingLayer (based on RuntimeDyld) in Orc. *| 12 | |* *| 13 | |* Many exotic languages can interoperate with C code but have a harder time *| 14 | |* with C++ due to name mangling. So in addition to C, this interface enables *| 15 | |* tools written in such languages. *| 16 | |* *| 17 | |* Note: This interface is experimental. It is *NOT* stable, and may be *| 18 | |* changed without warning. Only C API usage documentation is *| 19 | |* provided. See the C++ documentation for all higher level ORC API *| 20 | |* details. *| 21 | |* *| 22 | \*===----------------------------------------------------------------------===*/ 23 | 24 | #ifndef LLVM_C_ORCEE_H 25 | #define LLVM_C_ORCEE_H 26 | 27 | #include "llvm-c/Error.h" 28 | #include "llvm-c/ExecutionEngine.h" 29 | #include "llvm-c/Orc.h" 30 | #include "llvm-c/TargetMachine.h" 31 | #include "llvm-c/Types.h" 32 | 33 | LLVM_C_EXTERN_C_BEGIN 34 | 35 | /** 36 | * Create a RTDyldObjectLinkingLayer instance using the standard 37 | * SectionMemoryManager for memory management. 38 | */ 39 | LLVMOrcObjectLayerRef 40 | LLVMOrcCreateRTDyldObjectLinkingLayerWithSectionMemoryManager( 41 | LLVMOrcExecutionSessionRef ES); 42 | 43 | /** 44 | * Add the given listener to the given RTDyldObjectLinkingLayer. 45 | * 46 | * Note: Layer must be an RTDyldObjectLinkingLayer instance or 47 | * behavior is undefined. 48 | */ 49 | void LLVMOrcRTDyldObjectLinkingLayerRegisterJITEventListener( 50 | LLVMOrcObjectLayerRef RTDyldObjLinkingLayer, 51 | LLVMJITEventListenerRef Listener); 52 | 53 | LLVM_C_EXTERN_C_END 54 | 55 | #endif /* LLVM_C_ORCEE_H */ 56 | -------------------------------------------------------------------------------- /third-party/include/llvm-c/Analysis.h: -------------------------------------------------------------------------------- 1 | /*===-- llvm-c/Analysis.h - Analysis Library C Interface --------*- C++ -*-===*\ 2 | |* *| 3 | |* Part of the LLVM Project, under the Apache License v2.0 with LLVM *| 4 | |* Exceptions. *| 5 | |* See https://llvm.org/LICENSE.txt for license information. *| 6 | |* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception *| 7 | |* *| 8 | |*===----------------------------------------------------------------------===*| 9 | |* *| 10 | |* This header declares the C interface to libLLVMAnalysis.a, which *| 11 | |* implements various analyses of the LLVM IR. *| 12 | |* *| 13 | |* Many exotic languages can interoperate with C code but have a harder time *| 14 | |* with C++ due to name mangling. So in addition to C, this interface enables *| 15 | |* tools written in such languages. *| 16 | |* *| 17 | \*===----------------------------------------------------------------------===*/ 18 | 19 | #ifndef LLVM_C_ANALYSIS_H 20 | #define LLVM_C_ANALYSIS_H 21 | 22 | #include "llvm-c/ExternC.h" 23 | #include "llvm-c/Types.h" 24 | 25 | LLVM_C_EXTERN_C_BEGIN 26 | 27 | /** 28 | * @defgroup LLVMCAnalysis Analysis 29 | * @ingroup LLVMC 30 | * 31 | * @{ 32 | */ 33 | 34 | typedef enum { 35 | LLVMAbortProcessAction, /* verifier will print to stderr and abort() */ 36 | LLVMPrintMessageAction, /* verifier will print to stderr and return 1 */ 37 | LLVMReturnStatusAction /* verifier will just return 1 */ 38 | } LLVMVerifierFailureAction; 39 | 40 | 41 | /* Verifies that a module is valid, taking the specified action if not. 42 | Optionally returns a human-readable description of any invalid constructs. 43 | OutMessage must be disposed with LLVMDisposeMessage. */ 44 | LLVMBool LLVMVerifyModule(LLVMModuleRef M, LLVMVerifierFailureAction Action, 45 | char **OutMessage); 46 | 47 | /* Verifies that a single function is valid, taking the specified action. Useful 48 | for debugging. */ 49 | LLVMBool LLVMVerifyFunction(LLVMValueRef Fn, LLVMVerifierFailureAction Action); 50 | 51 | /* Open up a ghostview window that displays the CFG of the current function. 52 | Useful for debugging. */ 53 | void LLVMViewFunctionCFG(LLVMValueRef Fn); 54 | void LLVMViewFunctionCFGOnly(LLVMValueRef Fn); 55 | 56 | /** 57 | * @} 58 | */ 59 | 60 | LLVM_C_EXTERN_C_END 61 | 62 | #endif 63 | -------------------------------------------------------------------------------- /third-party/include/llvm-c/Comdat.h: -------------------------------------------------------------------------------- 1 | /*===-- llvm-c/Comdat.h - Module Comdat C Interface -------------*- C++ -*-===*\ 2 | |* *| 3 | |* Part of the LLVM Project, under the Apache License v2.0 with LLVM *| 4 | |* Exceptions. *| 5 | |* See https://llvm.org/LICENSE.txt for license information. *| 6 | |* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception *| 7 | |* *| 8 | |*===----------------------------------------------------------------------===*| 9 | |* *| 10 | |* This file defines the C interface to COMDAT. *| 11 | |* *| 12 | \*===----------------------------------------------------------------------===*/ 13 | 14 | #ifndef LLVM_C_COMDAT_H 15 | #define LLVM_C_COMDAT_H 16 | 17 | #include "llvm-c/ExternC.h" 18 | #include "llvm-c/Types.h" 19 | 20 | LLVM_C_EXTERN_C_BEGIN 21 | 22 | typedef enum { 23 | LLVMAnyComdatSelectionKind, ///< The linker may choose any COMDAT. 24 | LLVMExactMatchComdatSelectionKind, ///< The data referenced by the COMDAT must 25 | ///< be the same. 26 | LLVMLargestComdatSelectionKind, ///< The linker will choose the largest 27 | ///< COMDAT. 28 | LLVMNoDeduplicateComdatSelectionKind, ///< No deduplication is performed. 29 | LLVMSameSizeComdatSelectionKind ///< The data referenced by the COMDAT must be 30 | ///< the same size. 31 | } LLVMComdatSelectionKind; 32 | 33 | /** 34 | * Return the Comdat in the module with the specified name. It is created 35 | * if it didn't already exist. 36 | * 37 | * @see llvm::Module::getOrInsertComdat() 38 | */ 39 | LLVMComdatRef LLVMGetOrInsertComdat(LLVMModuleRef M, const char *Name); 40 | 41 | /** 42 | * Get the Comdat assigned to the given global object. 43 | * 44 | * @see llvm::GlobalObject::getComdat() 45 | */ 46 | LLVMComdatRef LLVMGetComdat(LLVMValueRef V); 47 | 48 | /** 49 | * Assign the Comdat to the given global object. 50 | * 51 | * @see llvm::GlobalObject::setComdat() 52 | */ 53 | void LLVMSetComdat(LLVMValueRef V, LLVMComdatRef C); 54 | 55 | /* 56 | * Get the conflict resolution selection kind for the Comdat. 57 | * 58 | * @see llvm::Comdat::getSelectionKind() 59 | */ 60 | LLVMComdatSelectionKind LLVMGetComdatSelectionKind(LLVMComdatRef C); 61 | 62 | /* 63 | * Set the conflict resolution selection kind for the Comdat. 64 | * 65 | * @see llvm::Comdat::setSelectionKind() 66 | */ 67 | void LLVMSetComdatSelectionKind(LLVMComdatRef C, LLVMComdatSelectionKind Kind); 68 | 69 | LLVM_C_EXTERN_C_END 70 | 71 | #endif 72 | -------------------------------------------------------------------------------- /source/base/mem.h: -------------------------------------------------------------------------------- 1 | /* date = September 27th 2021 11:45 am */ 2 | 3 | #ifndef MEM_H 4 | #define MEM_H 5 | 6 | #include 7 | #include "defines.h" 8 | 9 | //~ Arena (Linear Allocator) 10 | 11 | typedef struct M_Arena { 12 | u64 max; 13 | u64 alloc_position; 14 | u64 commit_position; 15 | b8 static_size; 16 | // u8* memory starts from this point 17 | } M_Arena; 18 | 19 | #define M_ARENA_MAX Gigabytes(1) 20 | #define M_ARENA_COMMIT_SIZE Kilobytes(8) 21 | 22 | M_Arena* arena_make(void); 23 | M_Arena* arena_make_sized(u64 max); 24 | void arena_clear(M_Arena* arena); 25 | void arena_free(M_Arena* arena); 26 | 27 | void* arena_alloc(M_Arena* arena, u64 size); 28 | void* arena_alloc_zero(M_Arena* arena, u64 size); 29 | void arena_dealloc(M_Arena* arena, u64 size); 30 | void arena_dealloc_to(M_Arena* arena, u64 pos); 31 | void* arena_raise(M_Arena* arena, void* ptr, u64 size); 32 | void* arena_alloc_array_sized(M_Arena* arena, u64 elem_size, u64 count); 33 | 34 | #define arena_alloc_array(arena, elem_type, count) \ 35 | arena_alloc_array_sized(arena, sizeof(elem_type), count) 36 | 37 | typedef struct M_ArenaTemp { 38 | M_Arena* arena; 39 | u64 pos; 40 | } M_ArenaTemp; 41 | 42 | M_ArenaTemp arena_begin_temp(M_Arena* arena); 43 | void arena_end_temp(M_ArenaTemp temp); 44 | 45 | //~ Scratch Helpers 46 | 47 | typedef struct M_Scratch { 48 | M_Arena* arena; 49 | u64 pos; 50 | } M_Scratch; 51 | 52 | void M_ScratchInit(void); 53 | void M_ScratchFree(void); 54 | 55 | M_Scratch scratch_get(M_Arena** conflict_array, u32 count); 56 | void scratch_reset(M_Scratch* scratch); 57 | void scratch_return(M_Scratch* scratch); 58 | 59 | //~ Pool Allocator 60 | 61 | typedef struct M_PoolFreeNode M_PoolFreeNode; 62 | struct M_PoolFreeNode { M_PoolFreeNode* next; }; 63 | 64 | typedef struct M_Pool { 65 | u64 max; 66 | u64 commit_position; 67 | u64 element_size; 68 | 69 | M_PoolFreeNode* head; 70 | } M_Pool; 71 | 72 | #define M_POOL_MAX Gigabytes(1) 73 | #define M_POOL_COMMIT_CHUNK 32 74 | 75 | M_Pool* pool_make(u64 element_size); 76 | void pool_clear(M_Pool* pool); 77 | void pool_free(M_Pool* pool); 78 | 79 | void* pool_alloc(M_Pool* pool); 80 | void pool_dealloc(M_Pool* pool, void* ptr); 81 | void pool_dealloc_range(M_Pool* pool, void* ptr, u64 count); 82 | 83 | //~ Heap Allocator 84 | 85 | typedef struct M_HeapFreeNode M_HeapFreeNode; 86 | struct M_HeapFreeNode { M_HeapFreeNode* next; u64 size; }; 87 | 88 | typedef struct M_Heap { 89 | u64 max; 90 | u64 commit_position; 91 | 92 | M_HeapFreeNode* head; 93 | } M_Heap; 94 | 95 | #define M_HEAP_MAX Gigabytes(1) 96 | #define M_HEAP_COMMIT_SIZE Kilobytes(8) 97 | 98 | M_Heap* heap_make(void); 99 | void heap_clear(M_Heap* heap); 100 | void heap_free(M_Heap* heap); 101 | 102 | void* heap_alloc(M_Heap* heap, u64 size); 103 | void heap_dealloc(M_Heap* heap, void* ptr, u64 size); 104 | 105 | #endif //MEM_H 106 | -------------------------------------------------------------------------------- /source/lexer.h: -------------------------------------------------------------------------------- 1 | /* date = October 7th 2021 11:58 am */ 2 | 3 | #ifndef LEXER_H 4 | #define LEXER_H 5 | 6 | #include "defines.h" 7 | #include "base/str.h" 8 | 9 | typedef u32 L_TokenType; 10 | 11 | enum { 12 | TokenType_Error, TokenType_EOF, 13 | 14 | TokenType_Ident, TokenType_CstringLit, 15 | TokenType_IntLit, TokenType_FloatLit, TokenType_DoubleLit, TokenType_CharLit, 16 | TokenType_LongLit, 17 | 18 | TokenType_Plus, TokenType_Minus, TokenType_Star, TokenType_Slash, 19 | TokenType_Ampersand, TokenType_Pipe, 20 | TokenType_Tilde, TokenType_Bang, 21 | TokenType_BangEqual, TokenType_EqualEqual, 22 | TokenType_Less, TokenType_Greater, 23 | TokenType_LessEqual, TokenType_GreaterEqual, 24 | TokenType_AmpersandAmpersand, TokenType_PipePipe, 25 | TokenType_ShiftLeft, TokenType_ShiftRight, 26 | 27 | TokenType_Percent, 28 | TokenType_PlusPlus, TokenType_MinusMinus, 29 | TokenType_Backslash, TokenType_Hat, TokenType_Equal, 30 | TokenType_PlusEqual, TokenType_MinusEqual, TokenType_StarEqual, 31 | TokenType_SlashEqual, TokenType_PercentEqual, TokenType_AmpersandEqual, 32 | TokenType_PipeEqual, 33 | TokenType_HatEqual, TokenType_TildeEqual, 34 | 35 | TokenType_OpenBrace, TokenType_OpenParenthesis, TokenType_OpenBracket, 36 | TokenType_CloseBrace, TokenType_CloseParenthesis, TokenType_CloseBracket, 37 | TokenType_Comma, TokenType_Dot, TokenType_Ellipses, TokenType_Semicolon, 38 | TokenType_Colon, TokenType_Question, TokenType_Arrow, TokenType_ThinArrow, 39 | 40 | TokenType_Struct, TokenType_Enum, TokenType_Union, TokenType_FlagEnum, 41 | TokenType_Return, TokenType_Break, TokenType_Continue, TokenType_Import, 42 | TokenType_Null, TokenType_Nullptr, TokenType_Const, 43 | TokenType_If, TokenType_Else, TokenType_Do, TokenType_For, TokenType_While, 44 | TokenType_Switch, TokenType_Match, TokenType_Case, TokenType_Default, 45 | TokenType_True, TokenType_False, TokenType_Native, 46 | TokenType_Namespace, TokenType_Using, 47 | TokenType_Int, TokenType_Cstring, TokenType_Float, TokenType_Bool, 48 | TokenType_Double, TokenType_Char, TokenType_Short, TokenType_Long, 49 | TokenType_Void, TokenType_Uchar, TokenType_Ushort, 50 | TokenType_Uint, TokenType_Ulong, 51 | TokenType_Func, 52 | 53 | TokenType_Tag, TokenType_Sizeof, TokenType_Offsetof, TokenType_Cinclude, 54 | TokenType_Cinsert, TokenType_Operator, TokenType_Typedef, 55 | 56 | TokenType_Print, 57 | 58 | TokenType_TokenTypeCount 59 | }; 60 | 61 | typedef struct __L_TokenTypeStringPair { 62 | L_TokenType type; 63 | string name; 64 | } __L_TokenTypeStringPair; 65 | 66 | typedef struct L_Lexer { 67 | const char* start; 68 | const char* current; 69 | u32 line; 70 | u32 column; 71 | } L_Lexer; 72 | 73 | typedef struct L_Token { 74 | L_TokenType type; 75 | string lexeme; 76 | u32 line, column; 77 | } L_Token; 78 | 79 | void L_Init(L_Lexer* lexer, string source); 80 | L_Token L_LexToken(L_Lexer* lexer); 81 | void L_PrintToken(L_Token token); 82 | 83 | string L_GetTypeName(L_TokenType type); 84 | 85 | #endif //LEXER_H 86 | -------------------------------------------------------------------------------- /third-party/include/llvm-c/DataTypes.h: -------------------------------------------------------------------------------- 1 | /*===-- include/llvm-c/DataTypes.h - Define fixed size types ------*- C -*-===*\ 2 | |* *| 3 | |* Part of the LLVM Project, under the Apache License v2.0 with LLVM *| 4 | |* Exceptions. *| 5 | |* See https://llvm.org/LICENSE.txt for license information. *| 6 | |* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception *| 7 | |* *| 8 | |*===----------------------------------------------------------------------===*| 9 | |* *| 10 | |* This file contains definitions to figure out the size of _HOST_ data types.*| 11 | |* This file is important because different host OS's define different macros,*| 12 | |* which makes portability tough. This file exports the following *| 13 | |* definitions: *| 14 | |* *| 15 | |* [u]int(32|64)_t : typedefs for signed and unsigned 32/64 bit system types*| 16 | |* [U]INT(8|16|32|64)_(MIN|MAX) : Constants for the min and max values. *| 17 | |* *| 18 | |* No library is required when using these functions. *| 19 | |* *| 20 | |*===----------------------------------------------------------------------===*/ 21 | 22 | /* Please leave this file C-compatible. */ 23 | 24 | #ifndef LLVM_C_DATATYPES_H 25 | #define LLVM_C_DATATYPES_H 26 | 27 | #include 28 | #include 29 | 30 | #ifndef _MSC_VER 31 | 32 | #if !defined(UINT32_MAX) 33 | # error "The standard header is not C++11 compliant. Must #define "\ 34 | "__STDC_LIMIT_MACROS before #including llvm-c/DataTypes.h" 35 | #endif 36 | 37 | #if !defined(UINT32_C) 38 | # error "The standard header is not C++11 compliant. Must #define "\ 39 | "__STDC_CONSTANT_MACROS before #including llvm-c/DataTypes.h" 40 | #endif 41 | 42 | /* Note that includes , if this is a C99 system. */ 43 | #include 44 | 45 | #ifdef _AIX 46 | // GCC is strict about defining large constants: they must have LL modifier. 47 | #undef INT64_MAX 48 | #undef INT64_MIN 49 | #endif 50 | 51 | #else /* _MSC_VER */ 52 | #ifdef __cplusplus 53 | #include 54 | #include 55 | #else 56 | #include 57 | #include 58 | #endif 59 | #include 60 | 61 | #if defined(_WIN64) 62 | typedef signed __int64 ssize_t; 63 | #else 64 | typedef signed int ssize_t; 65 | #endif /* _WIN64 */ 66 | 67 | #endif /* _MSC_VER */ 68 | 69 | /* Set defaults for constants which we cannot find. */ 70 | #if !defined(INT64_MAX) 71 | # define INT64_MAX 9223372036854775807LL 72 | #endif 73 | #if !defined(INT64_MIN) 74 | # define INT64_MIN ((-INT64_MAX)-1) 75 | #endif 76 | #if !defined(UINT64_MAX) 77 | # define UINT64_MAX 0xffffffffffffffffULL 78 | #endif 79 | 80 | #endif /* LLVM_C_DATATYPES_H */ 81 | -------------------------------------------------------------------------------- /source/base/utils.c: -------------------------------------------------------------------------------- 1 | #include "utils.h" 2 | 3 | #include 4 | #include 5 | 6 | //~ Time 7 | 8 | U_DenseTime U_DenseTimeFromDateTime(U_DateTime* datetime) { 9 | u32 encoded = (u32)((s32)datetime->year + 0x8000); 10 | U_DenseTime result = 0; 11 | result += encoded; 12 | result *= 12; 13 | result += datetime->month; 14 | result *= 31; 15 | result += datetime->day; 16 | result *= 24; 17 | result += datetime->hour; 18 | result *= 60; 19 | result += datetime->minute; 20 | result *= 60; 21 | result += datetime->sec; 22 | result *= 1000; 23 | result += datetime->ms; 24 | return result; 25 | } 26 | 27 | U_DateTime U_DateTimeFromDenseTime(U_DenseTime densetime) { 28 | U_DateTime result = {0}; 29 | result.ms = densetime % 1000; 30 | densetime /= 1000; 31 | result.sec = densetime % 60; 32 | densetime /= 60; 33 | result.minute = densetime % 60; 34 | densetime /= 60; 35 | result.hour = densetime % 24; 36 | densetime /= 24; 37 | result.day = densetime % 31; 38 | densetime /= 31; 39 | result.month = densetime % 12; 40 | densetime /= 12; 41 | result.year = ((s32)densetime) - 0x8000; 42 | return result; 43 | } 44 | 45 | //~ Time 46 | 47 | string U_FixFilepath(M_Arena* arena, string filepath) { 48 | M_Scratch scratch = scratch_get(&arena, 1); 49 | 50 | string fixed = filepath; 51 | fixed = str_replace_all(scratch.arena, fixed, str_lit("\\"), str_lit("/")); 52 | fixed = str_replace_all(arena, fixed, str_lit("/./"), str_lit("/")); 53 | while (true) { 54 | u64 dotdot = str_find_first(fixed, str_lit(".."), 0); 55 | if (dotdot == fixed.size) break; 56 | 57 | u64 last_slash = str_find_last(fixed, str_lit("/"), dotdot - 1); 58 | 59 | u64 range = (dotdot + 3) - last_slash; 60 | string old = fixed; 61 | fixed = str_alloc(scratch.arena, fixed.size - range); 62 | memcpy(fixed.str, old.str, last_slash); 63 | memcpy(fixed.str + last_slash, old.str + dotdot + 3, old.size - range - last_slash + 1); 64 | } 65 | 66 | fixed = str_copy(arena, fixed); 67 | scratch_return(&scratch); 68 | 69 | return fixed; 70 | } 71 | 72 | string U_GetFullFilepath(M_Arena* arena, string filename) { 73 | M_Scratch scratch = scratch_get(&arena, 1); 74 | 75 | char buffer[PATH_MAX]; 76 | get_cwd(buffer, PATH_MAX); 77 | string cwd = { .str = (u8*) buffer, .size = strlen(buffer) }; 78 | 79 | string finalized = str_cat(scratch.arena, cwd, str_lit("/")); 80 | finalized = str_cat(scratch.arena, finalized, filename); 81 | finalized = U_FixFilepath(arena, finalized); 82 | 83 | scratch_return(&scratch); 84 | return finalized; 85 | } 86 | 87 | string U_GetFilenameFromFilepath(string filepath) { 88 | u64 last_slash = str_find_last(filepath, str_lit("/"), 0); 89 | 90 | if (last_slash == filepath.size) 91 | last_slash = 0; 92 | else if (last_slash == 0) 93 | last_slash = str_find_last(filepath, str_lit("\\"), 0); 94 | 95 | u64 sizeof_filename = filepath.size - last_slash; 96 | return (string) { .str = filepath.str + last_slash, .size = sizeof_filename }; 97 | } 98 | 99 | string U_GetDirectoryFromFilepath(string filepath) { 100 | u64 last_slash = str_find_last(filepath, str_lit("/"), 0); 101 | if (last_slash == 0) last_slash = str_find_last(filepath, str_lit("\\"), 0); 102 | return (string) { .str = filepath.str, .size = last_slash - 1 }; 103 | } 104 | -------------------------------------------------------------------------------- /third-party/include/llvm-c/Transforms/PassManagerBuilder.h: -------------------------------------------------------------------------------- 1 | /*===-- llvm-c/Transform/PassManagerBuilder.h - PMB C Interface ---*- C -*-===*\ 2 | |* *| 3 | |* Part of the LLVM Project, under the Apache License v2.0 with LLVM *| 4 | |* Exceptions. *| 5 | |* See https://llvm.org/LICENSE.txt for license information. *| 6 | |* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception *| 7 | |* *| 8 | |*===----------------------------------------------------------------------===*| 9 | |* *| 10 | |* This header declares the C interface to the PassManagerBuilder class. *| 11 | |* *| 12 | \*===----------------------------------------------------------------------===*/ 13 | 14 | #ifndef LLVM_C_TRANSFORMS_PASSMANAGERBUILDER_H 15 | #define LLVM_C_TRANSFORMS_PASSMANAGERBUILDER_H 16 | 17 | #include "llvm-c/ExternC.h" 18 | #include "llvm-c/Types.h" 19 | 20 | typedef struct LLVMOpaquePassManagerBuilder *LLVMPassManagerBuilderRef; 21 | 22 | LLVM_C_EXTERN_C_BEGIN 23 | 24 | /** 25 | * @defgroup LLVMCTransformsPassManagerBuilder Pass manager builder 26 | * @ingroup LLVMCTransforms 27 | * 28 | * @{ 29 | */ 30 | 31 | /** See llvm::PassManagerBuilder. */ 32 | LLVMPassManagerBuilderRef LLVMPassManagerBuilderCreate(void); 33 | void LLVMPassManagerBuilderDispose(LLVMPassManagerBuilderRef PMB); 34 | 35 | /** See llvm::PassManagerBuilder::OptLevel. */ 36 | void 37 | LLVMPassManagerBuilderSetOptLevel(LLVMPassManagerBuilderRef PMB, 38 | unsigned OptLevel); 39 | 40 | /** See llvm::PassManagerBuilder::SizeLevel. */ 41 | void 42 | LLVMPassManagerBuilderSetSizeLevel(LLVMPassManagerBuilderRef PMB, 43 | unsigned SizeLevel); 44 | 45 | /** See llvm::PassManagerBuilder::DisableUnitAtATime. */ 46 | void 47 | LLVMPassManagerBuilderSetDisableUnitAtATime(LLVMPassManagerBuilderRef PMB, 48 | LLVMBool Value); 49 | 50 | /** See llvm::PassManagerBuilder::DisableUnrollLoops. */ 51 | void 52 | LLVMPassManagerBuilderSetDisableUnrollLoops(LLVMPassManagerBuilderRef PMB, 53 | LLVMBool Value); 54 | 55 | /** See llvm::PassManagerBuilder::DisableSimplifyLibCalls */ 56 | void 57 | LLVMPassManagerBuilderSetDisableSimplifyLibCalls(LLVMPassManagerBuilderRef PMB, 58 | LLVMBool Value); 59 | 60 | /** See llvm::PassManagerBuilder::Inliner. */ 61 | void 62 | LLVMPassManagerBuilderUseInlinerWithThreshold(LLVMPassManagerBuilderRef PMB, 63 | unsigned Threshold); 64 | 65 | /** See llvm::PassManagerBuilder::populateFunctionPassManager. */ 66 | void 67 | LLVMPassManagerBuilderPopulateFunctionPassManager(LLVMPassManagerBuilderRef PMB, 68 | LLVMPassManagerRef PM); 69 | 70 | /** See llvm::PassManagerBuilder::populateModulePassManager. */ 71 | void 72 | LLVMPassManagerBuilderPopulateModulePassManager(LLVMPassManagerBuilderRef PMB, 73 | LLVMPassManagerRef PM); 74 | 75 | /** See llvm::PassManagerBuilder::populateLTOPassManager. */ 76 | void LLVMPassManagerBuilderPopulateLTOPassManager(LLVMPassManagerBuilderRef PMB, 77 | LLVMPassManagerRef PM, 78 | LLVMBool Internalize, 79 | LLVMBool RunInliner); 80 | 81 | /** 82 | * @} 83 | */ 84 | 85 | LLVM_C_EXTERN_C_END 86 | 87 | #endif 88 | -------------------------------------------------------------------------------- /source/defines.h: -------------------------------------------------------------------------------- 1 | /* date = September 27th 2021 11:48 am */ 2 | 3 | #ifndef DEFINES_H 4 | #define DEFINES_H 5 | 6 | #include 7 | 8 | // Unsigned int types. 9 | typedef unsigned char u8; 10 | typedef unsigned short u16; 11 | typedef unsigned int u32; 12 | typedef unsigned long long u64; 13 | 14 | // Signed int types. 15 | typedef signed char s8; 16 | typedef signed short s16; 17 | typedef signed int s32; 18 | typedef signed long long s64; 19 | 20 | // Regular int types. 21 | typedef char i8; 22 | typedef short i16; 23 | typedef int i32; 24 | typedef long long i64; 25 | 26 | // Floating point types 27 | typedef float f32; 28 | typedef double f64; 29 | 30 | // Boolean types 31 | typedef u8 b8; 32 | typedef u32 b32; 33 | 34 | // Void function type 35 | typedef void void_func(void); 36 | typedef void (*void_func_ptr)(void); 37 | 38 | #define true 1 39 | #define false 0 40 | 41 | #define null 0 42 | #define u32_max 4294967295 43 | 44 | #ifndef __cplusplus 45 | #define nullptr (void*)0 46 | #endif 47 | 48 | #if defined(__clang__) 49 | # define COMPILER_CLANG 50 | #elif defined(_MSC_VER) 51 | # define COMPILER_CL 52 | #elif defined(__GNUC__) 53 | # define COMPILER_GCC 54 | #endif 55 | 56 | #if defined(COMPILER_CLANG) 57 | # define FILE_NAME __FILE_NAME__ 58 | #else 59 | # define FILE_NAME __FILE__ 60 | #endif 61 | 62 | #define Statement(s) do {\ 63 | s\ 64 | } while (0) 65 | 66 | #define flush fflush(stdout) 67 | #define trace Statement(printf("%s:%d: Trace\n", FILE_NAME, __LINE__); flush;) 68 | #define unreachable Statement(\ 69 | printf("How did we get here? In %s on line %d\n", FILE_NAME, __LINE__);\ 70 | flush;\ 71 | ) 72 | 73 | #if defined(WIN32) || defined(_WIN32) || defined(__WIN32__) 74 | # define PLATFORM_WIN 75 | #elif defined(__linux__) || defined(__gnu_linux__) 76 | # define PLATFORM_LINUX 77 | #else 78 | # error "The compiler only supports windows and linux for now" 79 | #endif 80 | #define PATH_MAX 4096 81 | 82 | #ifdef PLATFORM_WIN 83 | # include 84 | # define get_cwd _getcwd 85 | #elif defined(PLATFORM_LINUX) 86 | # include 87 | # define get_cwd getcwd 88 | #endif 89 | 90 | // NOTE(voxel): Confirm gcc version works 91 | #if defined(COMPILER_CL) || defined(COMPILER_CLANG) 92 | # define dll_export __declspec(dllexport) 93 | # define dll_import __declspec(dllimport) 94 | #elif defined (COMPILER_GCC) 95 | # define dll_export __attribute__((dllexport)) 96 | # define dll_import __attribute__((dllimport)) 97 | #else 98 | # error dll_export not defined for this compiler 99 | #endif 100 | 101 | #ifdef PLUGIN 102 | # define dll_plugin_api 103 | #else 104 | # define dll_plugin_api dll_export 105 | #endif 106 | 107 | #define Gigabytes(count) (u64) (count * 1024 * 1024 * 1024) 108 | #define Megabytes(count) (u64) (count * 1024 * 1024) 109 | #define Kilobytes(count) (u64) (count * 1024) 110 | 111 | #define Min(a,b) (((a)<(b))?(a):(b)) 112 | #define Max(a,b) (((a)>(b))?(a):(b)) 113 | #define Clamp(a,x,b) (((x)<(a))?(a):((b)<(x))?(b):(x)) 114 | #define ClampTop(a,b) Min(a,b) 115 | #define ClampBot(a,b) Max(a,b) 116 | #define ReverseClamp(a,x,b) (((x)<(a))?(b):((b)<(x))?(a):(x)) 117 | #define Wrap(a,x,b) ReverseClamp(a,x,b) 118 | 119 | #define MemoryCopy(d,s,z) memmove((d), (s), (z)) 120 | #define MemoryCopyStruct(d,s) MemoryCopy((d),(s), Min(sizeof(*(d)) , sizeof(*(s)))) 121 | #define MemoryZero(d,z) memset((d), 0, (z)) 122 | #define MemoryZeroStruct(d,s) MemoryZero((d),sizeof(s)) 123 | 124 | #define ArrayCount(a) (sizeof(a) / sizeof(a[0])) 125 | 126 | #define Slice_Prototype(type) typedef struct type##_slice { type* elems; u32 len; } type##_slice; 127 | #define slice(type) type##_slice 128 | 129 | #define Iterate(array, var) for (int var = 0; var < array.len; var++) 130 | #define IteratePtr(array, var) for (int var = 0; var < array->len; var++) 131 | 132 | #endif //DEFINES_H -------------------------------------------------------------------------------- /third-party/include/llvm-c/Transforms/IPO.h: -------------------------------------------------------------------------------- 1 | /*===-- IPO.h - Interprocedural Transformations C Interface -----*- C++ -*-===*\ 2 | |* *| 3 | |* Part of the LLVM Project, under the Apache License v2.0 with LLVM *| 4 | |* Exceptions. *| 5 | |* See https://llvm.org/LICENSE.txt for license information. *| 6 | |* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception *| 7 | |* *| 8 | |*===----------------------------------------------------------------------===*| 9 | |* *| 10 | |* This header declares the C interface to libLLVMIPO.a, which implements *| 11 | |* various interprocedural transformations of the LLVM IR. *| 12 | |* *| 13 | \*===----------------------------------------------------------------------===*/ 14 | 15 | #ifndef LLVM_C_TRANSFORMS_IPO_H 16 | #define LLVM_C_TRANSFORMS_IPO_H 17 | 18 | #include "llvm-c/ExternC.h" 19 | #include "llvm-c/Types.h" 20 | 21 | LLVM_C_EXTERN_C_BEGIN 22 | 23 | /** 24 | * @defgroup LLVMCTransformsIPO Interprocedural transformations 25 | * @ingroup LLVMCTransforms 26 | * 27 | * @{ 28 | */ 29 | 30 | /** See llvm::createArgumentPromotionPass function. */ 31 | void LLVMAddArgumentPromotionPass(LLVMPassManagerRef PM); 32 | 33 | /** See llvm::createConstantMergePass function. */ 34 | void LLVMAddConstantMergePass(LLVMPassManagerRef PM); 35 | 36 | /** See llvm::createMergeFunctionsPass function. */ 37 | void LLVMAddMergeFunctionsPass(LLVMPassManagerRef PM); 38 | 39 | /** See llvm::createCalledValuePropagationPass function. */ 40 | void LLVMAddCalledValuePropagationPass(LLVMPassManagerRef PM); 41 | 42 | /** See llvm::createDeadArgEliminationPass function. */ 43 | void LLVMAddDeadArgEliminationPass(LLVMPassManagerRef PM); 44 | 45 | /** See llvm::createFunctionAttrsPass function. */ 46 | void LLVMAddFunctionAttrsPass(LLVMPassManagerRef PM); 47 | 48 | /** See llvm::createFunctionInliningPass function. */ 49 | void LLVMAddFunctionInliningPass(LLVMPassManagerRef PM); 50 | 51 | /** See llvm::createAlwaysInlinerPass function. */ 52 | void LLVMAddAlwaysInlinerPass(LLVMPassManagerRef PM); 53 | 54 | /** See llvm::createGlobalDCEPass function. */ 55 | void LLVMAddGlobalDCEPass(LLVMPassManagerRef PM); 56 | 57 | /** See llvm::createGlobalOptimizerPass function. */ 58 | void LLVMAddGlobalOptimizerPass(LLVMPassManagerRef PM); 59 | 60 | /** See llvm::createPruneEHPass function. */ 61 | void LLVMAddPruneEHPass(LLVMPassManagerRef PM); 62 | 63 | /** See llvm::createIPSCCPPass function. */ 64 | void LLVMAddIPSCCPPass(LLVMPassManagerRef PM); 65 | 66 | /** See llvm::createInternalizePass function. */ 67 | void LLVMAddInternalizePass(LLVMPassManagerRef, unsigned AllButMain); 68 | 69 | /** 70 | * Create and add the internalize pass to the given pass manager with the 71 | * provided preservation callback. 72 | * 73 | * The context parameter is forwarded to the callback on each invocation. 74 | * As such, it is the responsibility of the caller to extend its lifetime 75 | * until execution of this pass has finished. 76 | * 77 | * @see llvm::createInternalizePass function. 78 | */ 79 | void LLVMAddInternalizePassWithMustPreservePredicate( 80 | LLVMPassManagerRef PM, 81 | void *Context, 82 | LLVMBool (*MustPreserve)(LLVMValueRef, void *)); 83 | 84 | /** See llvm::createStripDeadPrototypesPass function. */ 85 | void LLVMAddStripDeadPrototypesPass(LLVMPassManagerRef PM); 86 | 87 | /** See llvm::createStripSymbolsPass function. */ 88 | void LLVMAddStripSymbolsPass(LLVMPassManagerRef PM); 89 | 90 | /** 91 | * @} 92 | */ 93 | 94 | LLVM_C_EXTERN_C_END 95 | 96 | #endif 97 | -------------------------------------------------------------------------------- /third-party/include/llvm/Config/llvm-config.h: -------------------------------------------------------------------------------- 1 | /*===------- llvm/Config/llvm-config.h - llvm configuration -------*- C -*-===*/ 2 | /* */ 3 | /* Part of the LLVM Project, under the Apache License v2.0 with LLVM */ 4 | /* Exceptions. */ 5 | /* See https://llvm.org/LICENSE.txt for license information. */ 6 | /* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception */ 7 | /* */ 8 | /*===----------------------------------------------------------------------===*/ 9 | 10 | /* This file enumerates variables from the LLVM configuration so that they 11 | can be in exported headers and won't override package specific directives. 12 | This is a C header that can be included in the llvm-c headers. */ 13 | 14 | #ifndef LLVM_CONFIG_H 15 | #define LLVM_CONFIG_H 16 | 17 | /* Define if LLVM_ENABLE_DUMP is enabled */ 18 | /* #undef LLVM_ENABLE_DUMP */ 19 | 20 | /* Target triple LLVM will generate code for by default */ 21 | #define LLVM_DEFAULT_TARGET_TRIPLE "x86_64-pc-windows-msvc" 22 | 23 | /* Define if threads enabled */ 24 | #define LLVM_ENABLE_THREADS 1 25 | 26 | /* Has gcc/MSVC atomic intrinsics */ 27 | #define LLVM_HAS_ATOMICS 1 28 | 29 | /* Host triple LLVM will be executed on */ 30 | #define LLVM_HOST_TRIPLE "x86_64-pc-windows-msvc" 31 | 32 | /* LLVM architecture name for the native architecture, if available */ 33 | #define LLVM_NATIVE_ARCH X86 34 | 35 | /* LLVM name for the native AsmParser init function, if available */ 36 | #define LLVM_NATIVE_ASMPARSER LLVMInitializeX86AsmParser 37 | 38 | /* LLVM name for the native AsmPrinter init function, if available */ 39 | #define LLVM_NATIVE_ASMPRINTER LLVMInitializeX86AsmPrinter 40 | 41 | /* LLVM name for the native Disassembler init function, if available */ 42 | #define LLVM_NATIVE_DISASSEMBLER LLVMInitializeX86Disassembler 43 | 44 | /* LLVM name for the native Target init function, if available */ 45 | #define LLVM_NATIVE_TARGET LLVMInitializeX86Target 46 | 47 | /* LLVM name for the native TargetInfo init function, if available */ 48 | #define LLVM_NATIVE_TARGETINFO LLVMInitializeX86TargetInfo 49 | 50 | /* LLVM name for the native target MC init function, if available */ 51 | #define LLVM_NATIVE_TARGETMC LLVMInitializeX86TargetMC 52 | 53 | /* Define if this is Unixish platform */ 54 | /* #undef LLVM_ON_UNIX */ 55 | 56 | /* Define if we have the Intel JIT API runtime support library */ 57 | #define LLVM_USE_INTEL_JITEVENTS 0 58 | 59 | /* Define if we have the oprofile JIT-support library */ 60 | #define LLVM_USE_OPROFILE 0 61 | 62 | /* Define if we have the perf JIT-support library */ 63 | #define LLVM_USE_PERF 0 64 | 65 | /* Major version of the LLVM API */ 66 | #define LLVM_VERSION_MAJOR 13 67 | 68 | /* Minor version of the LLVM API */ 69 | #define LLVM_VERSION_MINOR 0 70 | 71 | /* Patch version of the LLVM API */ 72 | #define LLVM_VERSION_PATCH 1 73 | 74 | /* LLVM version string */ 75 | #define LLVM_VERSION_STRING "13.0.1" 76 | 77 | /* Whether LLVM records statistics for use with GetStatistics(), 78 | * PrintStatistics() or PrintStatisticsJSON() 79 | */ 80 | #define LLVM_FORCE_ENABLE_STATS 0 81 | 82 | /* Define if we have z3 and want to build it */ 83 | /* #undef LLVM_WITH_Z3 */ 84 | 85 | /* Define if LLVM was built with a dependency to the libtensorflow dynamic library */ 86 | /* #undef LLVM_HAVE_TF_API */ 87 | 88 | /* Define if LLVM was built with a dependency to the tensorflow compiler */ 89 | /* #undef LLVM_HAVE_TF_AOT */ 90 | 91 | /* Define to 1 if you have the header file. */ 92 | /* #undef HAVE_SYSEXITS_H */ 93 | 94 | /* Define to 1 to enable the experimental new pass manager by default */ 95 | #define LLVM_ENABLE_NEW_PASS_MANAGER 1 96 | 97 | /* Define if the xar_open() function is supported on this platform. */ 98 | /* #undef LLVM_HAVE_LIBXAR */ 99 | 100 | /* Whether Timers signpost passes in Xcode Instruments */ 101 | #define LLVM_SUPPORT_XCODE_SIGNPOSTS 0 102 | 103 | 104 | #endif 105 | -------------------------------------------------------------------------------- /third-party/include/llvm-c/BitReader.h: -------------------------------------------------------------------------------- 1 | /*===-- llvm-c/BitReader.h - BitReader Library C Interface ------*- C++ -*-===*\ 2 | |* *| 3 | |* Part of the LLVM Project, under the Apache License v2.0 with LLVM *| 4 | |* Exceptions. *| 5 | |* See https://llvm.org/LICENSE.txt for license information. *| 6 | |* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception *| 7 | |* *| 8 | |*===----------------------------------------------------------------------===*| 9 | |* *| 10 | |* This header declares the C interface to libLLVMBitReader.a, which *| 11 | |* implements input of the LLVM bitcode format. *| 12 | |* *| 13 | |* Many exotic languages can interoperate with C code but have a harder time *| 14 | |* with C++ due to name mangling. So in addition to C, this interface enables *| 15 | |* tools written in such languages. *| 16 | |* *| 17 | \*===----------------------------------------------------------------------===*/ 18 | 19 | #ifndef LLVM_C_BITREADER_H 20 | #define LLVM_C_BITREADER_H 21 | 22 | #include "llvm-c/ExternC.h" 23 | #include "llvm-c/Types.h" 24 | 25 | LLVM_C_EXTERN_C_BEGIN 26 | 27 | /** 28 | * @defgroup LLVMCBitReader Bit Reader 29 | * @ingroup LLVMC 30 | * 31 | * @{ 32 | */ 33 | 34 | /* Builds a module from the bitcode in the specified memory buffer, returning a 35 | reference to the module via the OutModule parameter. Returns 0 on success. 36 | Optionally returns a human-readable error message via OutMessage. 37 | 38 | This is deprecated. Use LLVMParseBitcode2. */ 39 | LLVMBool LLVMParseBitcode(LLVMMemoryBufferRef MemBuf, LLVMModuleRef *OutModule, 40 | char **OutMessage); 41 | 42 | /* Builds a module from the bitcode in the specified memory buffer, returning a 43 | reference to the module via the OutModule parameter. Returns 0 on success. */ 44 | LLVMBool LLVMParseBitcode2(LLVMMemoryBufferRef MemBuf, 45 | LLVMModuleRef *OutModule); 46 | 47 | /* This is deprecated. Use LLVMParseBitcodeInContext2. */ 48 | LLVMBool LLVMParseBitcodeInContext(LLVMContextRef ContextRef, 49 | LLVMMemoryBufferRef MemBuf, 50 | LLVMModuleRef *OutModule, char **OutMessage); 51 | 52 | LLVMBool LLVMParseBitcodeInContext2(LLVMContextRef ContextRef, 53 | LLVMMemoryBufferRef MemBuf, 54 | LLVMModuleRef *OutModule); 55 | 56 | /** Reads a module from the specified path, returning via the OutMP parameter 57 | a module provider which performs lazy deserialization. Returns 0 on success. 58 | Optionally returns a human-readable error message via OutMessage. 59 | This is deprecated. Use LLVMGetBitcodeModuleInContext2. */ 60 | LLVMBool LLVMGetBitcodeModuleInContext(LLVMContextRef ContextRef, 61 | LLVMMemoryBufferRef MemBuf, 62 | LLVMModuleRef *OutM, char **OutMessage); 63 | 64 | /** Reads a module from the specified path, returning via the OutMP parameter a 65 | * module provider which performs lazy deserialization. Returns 0 on success. */ 66 | LLVMBool LLVMGetBitcodeModuleInContext2(LLVMContextRef ContextRef, 67 | LLVMMemoryBufferRef MemBuf, 68 | LLVMModuleRef *OutM); 69 | 70 | /* This is deprecated. Use LLVMGetBitcodeModule2. */ 71 | LLVMBool LLVMGetBitcodeModule(LLVMMemoryBufferRef MemBuf, LLVMModuleRef *OutM, 72 | char **OutMessage); 73 | 74 | LLVMBool LLVMGetBitcodeModule2(LLVMMemoryBufferRef MemBuf, LLVMModuleRef *OutM); 75 | 76 | /** 77 | * @} 78 | */ 79 | 80 | LLVM_C_EXTERN_C_END 81 | 82 | #endif 83 | -------------------------------------------------------------------------------- /source/checker.c: -------------------------------------------------------------------------------- 1 | #include "checker.h" 2 | 3 | //~ Type Cache 4 | 5 | DArray_Impl(Type); 6 | 7 | void TypeCache_Init(TypeCache* cache) { 8 | darray_reserve(Type, cache, TypeID_COUNT); 9 | } 10 | 11 | TypeID TypeCache_Register(TypeCache* cache, Type type) { 12 | IteratePtr(cache, i) { 13 | if (memcmp(&cache->elems[i], &type, sizeof(Type)) == 0) { 14 | return i; 15 | } 16 | } 17 | darray_add(Type, cache, type); 18 | return cache->len - 1; 19 | } 20 | 21 | // NOTE(voxel): @unsafe IF YOU DON'T KNOW WHAT YOU'RE DOING 22 | // NOTE(voxel): ALWAYS USE TypeCache_Register 23 | static void TypeCache_RegisterWithID(TypeCache* cache, Type type, TypeID id) { 24 | cache->elems[id] = type; 25 | } 26 | 27 | Type* TypeCache_Get(TypeCache* cache, TypeID id) { 28 | return &cache->elems[id]; 29 | } 30 | 31 | void TypeCache_Free(TypeCache* cache) { 32 | darray_free(Type, cache); 33 | } 34 | 35 | //~ Type Check 36 | 37 | #include "tables.h" 38 | 39 | static TypeID C_GetTypeAssociatedPair(TypePair* bindings, TypeID a) { 40 | for (u32 k = 0; ; k++) { 41 | if (bindings[k].a == TypeID_Invalid) break; 42 | if (bindings[k].a == a) { 43 | return bindings[k].r; 44 | } 45 | } 46 | return TypeID_Invalid; 47 | } 48 | 49 | static TypeID C_GetTypeAssociatedTriple(TypeTriple* bindings, TypeID a, TypeID b) { 50 | for (u32 k = 0; ; k++) { 51 | if (bindings[k].a == TypeID_Invalid) break; 52 | if (bindings[k].a == a && bindings[k].b == b) { 53 | return bindings[k].r; 54 | } 55 | } 56 | return TypeID_Invalid; 57 | } 58 | 59 | 60 | //~ Checker 61 | 62 | static TypeID C_CheckUnaryOp(TypeID operand, L_TokenType op) { 63 | TypeID ret = 0; 64 | if (op == TokenType_Plus || op == TokenType_Minus) { 65 | ret = C_GetTypeAssociatedPair(unary_operator_table_plusminus, operand); 66 | } else { 67 | // TODO(voxel): Error 68 | ret = TypeID_Invalid; 69 | } 70 | return ret; 71 | } 72 | 73 | static TypeID C_CheckBinaryOp(TypeID a, TypeID b, L_TokenType op) { 74 | TypeID ret = 0; 75 | if (op == TokenType_Plus || op == TokenType_Minus) { 76 | ret = C_GetTypeAssociatedTriple(binary_operator_table_plusminus, a, b); 77 | } else if (op == TokenType_Star || op == TokenType_Slash) { 78 | ret = C_GetTypeAssociatedTriple(binary_operator_table_stardivmod, a, b); 79 | } else { 80 | // TODO(voxel): Error 81 | ret = TypeID_Invalid; 82 | } 83 | return ret; 84 | } 85 | 86 | static TypeID C_CheckAst(IR_Ast* ast) { 87 | switch (ast->type) { 88 | case AstType_IntLiteral: { 89 | return TypeID_Integer; 90 | } break; 91 | 92 | case AstType_FloatLiteral: { 93 | // TODO(voxel): 94 | return TypeID_Invalid; 95 | } break; 96 | 97 | case AstType_ExprUnary: { 98 | TypeID operand_type = C_CheckAst(ast->unary.operand); 99 | return C_CheckUnaryOp(operand_type, ast->unary.operator.type); 100 | } break; 101 | 102 | case AstType_ExprBinary: { 103 | TypeID a_type = C_CheckAst(ast->binary.a); 104 | TypeID b_type = C_CheckAst(ast->binary.b); 105 | return C_CheckBinaryOp(a_type, b_type, ast->binary.operator.type); 106 | } break; 107 | 108 | case AstType_StmtPrint: return C_CheckAst(ast->print.value); 109 | } 110 | return TypeID_Invalid; 111 | } 112 | 113 | b8 C_Check(C_Checker* checker) { 114 | C_CheckAst(checker->ast); 115 | return !checker->errored; 116 | } 117 | 118 | void C_Init(C_Checker* checker, IR_Ast* ast) { 119 | MemoryZeroStruct(checker, C_Checker); 120 | checker->ast = ast; 121 | 122 | TypeCache_Init(&checker->type_cache); 123 | 124 | // NOTE(voxel): Register basic types so compiletime tables can be supah quick 125 | // NOTE(voxel): TypeCache_Init reserves the amount of space required 126 | // NOTE(voxel): so this unsafe code should be fine 127 | // NOTE(voxel): But remember to add name to TypeID_ enum before registering here 128 | TypeCache_RegisterWithID(&checker->type_cache, (Type) { 129 | .kind = TypeKind_Invalid 130 | }, TypeID_Invalid); 131 | TypeCache_RegisterWithID(&checker->type_cache, (Type) { 132 | .kind = TypeKind_Regular, 133 | .regular = RegularTypeKind_Integer 134 | }, TypeID_Integer); 135 | 136 | } 137 | 138 | void C_Free(C_Checker* checker) { 139 | TypeCache_Free(&checker->type_cache); 140 | } -------------------------------------------------------------------------------- /third-party/include/llvm/Config/llvm-config.h.cmake: -------------------------------------------------------------------------------- 1 | /*===------- llvm/Config/llvm-config.h - llvm configuration -------*- C -*-===*/ 2 | /* */ 3 | /* Part of the LLVM Project, under the Apache License v2.0 with LLVM */ 4 | /* Exceptions. */ 5 | /* See https://llvm.org/LICENSE.txt for license information. */ 6 | /* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception */ 7 | /* */ 8 | /*===----------------------------------------------------------------------===*/ 9 | 10 | /* This file enumerates variables from the LLVM configuration so that they 11 | can be in exported headers and won't override package specific directives. 12 | This is a C header that can be included in the llvm-c headers. */ 13 | 14 | #ifndef LLVM_CONFIG_H 15 | #define LLVM_CONFIG_H 16 | 17 | /* Define if LLVM_ENABLE_DUMP is enabled */ 18 | #cmakedefine LLVM_ENABLE_DUMP 19 | 20 | /* Target triple LLVM will generate code for by default */ 21 | #cmakedefine LLVM_DEFAULT_TARGET_TRIPLE "${LLVM_DEFAULT_TARGET_TRIPLE}" 22 | 23 | /* Define if threads enabled */ 24 | #cmakedefine01 LLVM_ENABLE_THREADS 25 | 26 | /* Has gcc/MSVC atomic intrinsics */ 27 | #cmakedefine01 LLVM_HAS_ATOMICS 28 | 29 | /* Host triple LLVM will be executed on */ 30 | #cmakedefine LLVM_HOST_TRIPLE "${LLVM_HOST_TRIPLE}" 31 | 32 | /* LLVM architecture name for the native architecture, if available */ 33 | #cmakedefine LLVM_NATIVE_ARCH ${LLVM_NATIVE_ARCH} 34 | 35 | /* LLVM name for the native AsmParser init function, if available */ 36 | #cmakedefine LLVM_NATIVE_ASMPARSER LLVMInitialize${LLVM_NATIVE_ARCH}AsmParser 37 | 38 | /* LLVM name for the native AsmPrinter init function, if available */ 39 | #cmakedefine LLVM_NATIVE_ASMPRINTER LLVMInitialize${LLVM_NATIVE_ARCH}AsmPrinter 40 | 41 | /* LLVM name for the native Disassembler init function, if available */ 42 | #cmakedefine LLVM_NATIVE_DISASSEMBLER LLVMInitialize${LLVM_NATIVE_ARCH}Disassembler 43 | 44 | /* LLVM name for the native Target init function, if available */ 45 | #cmakedefine LLVM_NATIVE_TARGET LLVMInitialize${LLVM_NATIVE_ARCH}Target 46 | 47 | /* LLVM name for the native TargetInfo init function, if available */ 48 | #cmakedefine LLVM_NATIVE_TARGETINFO LLVMInitialize${LLVM_NATIVE_ARCH}TargetInfo 49 | 50 | /* LLVM name for the native target MC init function, if available */ 51 | #cmakedefine LLVM_NATIVE_TARGETMC LLVMInitialize${LLVM_NATIVE_ARCH}TargetMC 52 | 53 | /* Define if this is Unixish platform */ 54 | #cmakedefine LLVM_ON_UNIX ${LLVM_ON_UNIX} 55 | 56 | /* Define if we have the Intel JIT API runtime support library */ 57 | #cmakedefine01 LLVM_USE_INTEL_JITEVENTS 58 | 59 | /* Define if we have the oprofile JIT-support library */ 60 | #cmakedefine01 LLVM_USE_OPROFILE 61 | 62 | /* Define if we have the perf JIT-support library */ 63 | #cmakedefine01 LLVM_USE_PERF 64 | 65 | /* Major version of the LLVM API */ 66 | #define LLVM_VERSION_MAJOR ${LLVM_VERSION_MAJOR} 67 | 68 | /* Minor version of the LLVM API */ 69 | #define LLVM_VERSION_MINOR ${LLVM_VERSION_MINOR} 70 | 71 | /* Patch version of the LLVM API */ 72 | #define LLVM_VERSION_PATCH ${LLVM_VERSION_PATCH} 73 | 74 | /* LLVM version string */ 75 | #define LLVM_VERSION_STRING "${PACKAGE_VERSION}" 76 | 77 | /* Whether LLVM records statistics for use with GetStatistics(), 78 | * PrintStatistics() or PrintStatisticsJSON() 79 | */ 80 | #cmakedefine01 LLVM_FORCE_ENABLE_STATS 81 | 82 | /* Define if we have z3 and want to build it */ 83 | #cmakedefine LLVM_WITH_Z3 ${LLVM_WITH_Z3} 84 | 85 | /* Define if LLVM was built with a dependency to the libtensorflow dynamic library */ 86 | #cmakedefine LLVM_HAVE_TF_API 87 | 88 | /* Define if LLVM was built with a dependency to the tensorflow compiler */ 89 | #cmakedefine LLVM_HAVE_TF_AOT 90 | 91 | /* Define to 1 if you have the header file. */ 92 | #cmakedefine HAVE_SYSEXITS_H ${HAVE_SYSEXITS_H} 93 | 94 | /* Define to 1 to enable the experimental new pass manager by default */ 95 | #cmakedefine01 LLVM_ENABLE_NEW_PASS_MANAGER 96 | 97 | /* Define if the xar_open() function is supported on this platform. */ 98 | #cmakedefine LLVM_HAVE_LIBXAR ${LLVM_HAVE_LIBXAR} 99 | 100 | /* Whether Timers signpost passes in Xcode Instruments */ 101 | #cmakedefine01 LLVM_SUPPORT_XCODE_SIGNPOSTS 102 | 103 | 104 | #endif 105 | -------------------------------------------------------------------------------- /third-party/include/llvm-c/Transforms/PassBuilder.h: -------------------------------------------------------------------------------- 1 | /*===-- llvm-c/Transform/PassBuilder.h - PassBuilder for LLVM C ---*- C -*-===*\ 2 | |* *| 3 | |* Part of the LLVM Project, under the Apache License v2.0 with LLVM *| 4 | |* Exceptions. *| 5 | |* See https://llvm.org/LICENSE.txt for license information. *| 6 | |* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception *| 7 | |* *| 8 | |*===----------------------------------------------------------------------===*| 9 | |* *| 10 | |* This header contains the LLVM-C interface into the new pass manager *| 11 | |* *| 12 | \*===----------------------------------------------------------------------===*/ 13 | 14 | #ifndef LLVM_C_TRANSFORMS_PASSBUILDER_H 15 | #define LLVM_C_TRANSFORMS_PASSBUILDER_H 16 | 17 | #include "llvm-c/Error.h" 18 | #include "llvm-c/TargetMachine.h" 19 | #include "llvm-c/Types.h" 20 | 21 | LLVM_C_EXTERN_C_BEGIN 22 | 23 | /** 24 | * A set of options passed which are attached to the Pass Manager upon run. 25 | * 26 | * This corresponds to an llvm::LLVMPassBuilderOptions instance 27 | * 28 | * The details for how the different properties of this structure are used can 29 | * be found in the source for LLVMRunPasses 30 | */ 31 | typedef struct LLVMOpaquePassBuilderOptions *LLVMPassBuilderOptionsRef; 32 | 33 | /** 34 | * Construct and run a set of passes over a module 35 | * 36 | * This function takes a string with the passes that should be used. The format 37 | * of this string is the same as opt's -passes argument for the new pass 38 | * manager. Individual passes may be specified, separated by commas. Full 39 | * pipelines may also be invoked using `default` and friends. See opt for 40 | * full reference of the Passes format. 41 | */ 42 | LLVMErrorRef LLVMRunPasses(LLVMModuleRef M, const char *Passes, 43 | LLVMTargetMachineRef TM, 44 | LLVMPassBuilderOptionsRef Options); 45 | 46 | /** 47 | * Create a new set of options for a PassBuilder 48 | * 49 | * Ownership of the returned instance is given to the client, and they are 50 | * responsible for it. The client should call LLVMDisposePassBuilderOptions 51 | * to free the pass builder options. 52 | */ 53 | LLVMPassBuilderOptionsRef LLVMCreatePassBuilderOptions(); 54 | 55 | /** 56 | * Toggle adding the VerifierPass for the PassBuilder, ensuring all functions 57 | * inside the module is valid. 58 | */ 59 | void LLVMPassBuilderOptionsSetVerifyEach(LLVMPassBuilderOptionsRef Options, 60 | LLVMBool VerifyEach); 61 | 62 | /** 63 | * Toggle debug logging when running the PassBuilder 64 | */ 65 | void LLVMPassBuilderOptionsSetDebugLogging(LLVMPassBuilderOptionsRef Options, 66 | LLVMBool DebugLogging); 67 | 68 | void LLVMPassBuilderOptionsSetLoopInterleaving( 69 | LLVMPassBuilderOptionsRef Options, LLVMBool LoopInterleaving); 70 | 71 | void LLVMPassBuilderOptionsSetLoopVectorization( 72 | LLVMPassBuilderOptionsRef Options, LLVMBool LoopVectorization); 73 | 74 | void LLVMPassBuilderOptionsSetSLPVectorization( 75 | LLVMPassBuilderOptionsRef Options, LLVMBool SLPVectorization); 76 | 77 | void LLVMPassBuilderOptionsSetLoopUnrolling(LLVMPassBuilderOptionsRef Options, 78 | LLVMBool LoopUnrolling); 79 | 80 | void LLVMPassBuilderOptionsSetForgetAllSCEVInLoopUnroll( 81 | LLVMPassBuilderOptionsRef Options, LLVMBool ForgetAllSCEVInLoopUnroll); 82 | 83 | void LLVMPassBuilderOptionsSetLicmMssaOptCap(LLVMPassBuilderOptionsRef Options, 84 | unsigned LicmMssaOptCap); 85 | 86 | void LLVMPassBuilderOptionsSetLicmMssaNoAccForPromotionCap( 87 | LLVMPassBuilderOptionsRef Options, unsigned LicmMssaNoAccForPromotionCap); 88 | 89 | void LLVMPassBuilderOptionsSetCallGraphProfile( 90 | LLVMPassBuilderOptionsRef Options, LLVMBool CallGraphProfile); 91 | 92 | void LLVMPassBuilderOptionsSetMergeFunctions(LLVMPassBuilderOptionsRef Options, 93 | LLVMBool MergeFunctions); 94 | 95 | /** 96 | * Dispose of a heap-allocated PassBuilderOptions instance 97 | */ 98 | void LLVMDisposePassBuilderOptions(LLVMPassBuilderOptionsRef Options); 99 | 100 | LLVM_C_EXTERN_C_END 101 | 102 | #endif // LLVM_C_TRANSFORMS_PASSBUILDER_H 103 | -------------------------------------------------------------------------------- /source/vm.c: -------------------------------------------------------------------------------- 1 | #include "vm.h" 2 | #include 3 | 4 | DArray_Impl(u8); 5 | Stack_Impl(VM_RuntimeValue); 6 | 7 | 8 | // For completeness' sake 9 | IR_Chunk IR_ChunkAlloc(void) { 10 | IR_Chunk chunk = {0}; 11 | return chunk; 12 | } 13 | 14 | void IR_ChunkPushOp(IR_Chunk* chunk, u8 byte) { 15 | darray_add(u8, chunk, byte); 16 | } 17 | 18 | void IR_ChunkPushU32(IR_Chunk* chunk, u32 val) { 19 | darray_add_all(u8, chunk, (u8*)&val, sizeof(u32)); 20 | } 21 | 22 | void IR_ChunkPush(IR_Chunk* chunk, u8* bytes, u32 count) { 23 | darray_add_all(u8, chunk, bytes, count); 24 | } 25 | 26 | void IR_ChunkFree(IR_Chunk* chunk) { 27 | darray_free(u8, chunk); 28 | } 29 | 30 | //~ VM Helpers 31 | 32 | void VM_Lower(IR_Chunk* chunk, IR_Ast* ast) { 33 | switch (ast->type) { 34 | case AstType_IntLiteral: { 35 | IR_ChunkPushOp(chunk, Opcode_Push); 36 | VM_RuntimeValue value = { 37 | .type = RuntimeValueType_Integer, 38 | .as_int = ast->int_lit.value, 39 | }; 40 | IR_ChunkPush(chunk, &value, sizeof(VM_RuntimeValue)); 41 | } break; 42 | 43 | case AstType_FloatLiteral: { 44 | // TODO(voxel): 45 | } break; 46 | 47 | case AstType_ExprUnary: { 48 | VM_Lower(chunk, ast->unary.operand); 49 | IR_ChunkPushOp(chunk, Opcode_UnaryOp); 50 | IR_ChunkPushU32(chunk, ast->unary.operator.type); 51 | } break; 52 | 53 | case AstType_ExprBinary: { 54 | VM_Lower(chunk, ast->binary.a); 55 | VM_Lower(chunk, ast->binary.b); 56 | IR_ChunkPushOp(chunk, Opcode_BinaryOp); 57 | IR_ChunkPushU32(chunk, ast->binary.operator.type); 58 | } break; 59 | 60 | case AstType_StmtPrint: { 61 | VM_Lower(chunk, ast->print.value); 62 | IR_ChunkPushOp(chunk, Opcode_Print); 63 | } break; 64 | 65 | default: {} break; 66 | } 67 | } 68 | 69 | IR_Chunk VM_LowerConstexpr(IR_Ast* ast) { 70 | IR_Chunk chunk = IR_ChunkAlloc(); 71 | VM_Lower(&chunk, ast); 72 | return chunk; 73 | } 74 | 75 | 76 | static VM_RuntimeValue VM_BinaryOp(VM_RuntimeValue v1, VM_RuntimeValue v2, L_TokenType op) { 77 | if (v1.type == RuntimeValueType_Integer && v2.type == RuntimeValueType_Integer) { 78 | switch (op) { 79 | case TokenType_Plus: v1.as_int = v1.as_int + v2.as_int; break; 80 | case TokenType_Minus: v1.as_int = v1.as_int - v2.as_int; break; 81 | case TokenType_Star: v1.as_int = v1.as_int * v2.as_int; break; 82 | case TokenType_Slash: v1.as_int = v1.as_int / v2.as_int; break; 83 | case TokenType_Percent: v1.as_int = v1.as_int % v2.as_int; break; 84 | } 85 | } else { 86 | // TODO(voxel): Error Invalid type pair 87 | } 88 | return v1; 89 | } 90 | 91 | 92 | static VM_RuntimeValue VM_UnaryOp(VM_RuntimeValue value, L_TokenType op) { 93 | if (value.type == RuntimeValueType_Integer) { 94 | if (op == TokenType_Plus) { 95 | // NO OP 96 | } else if (op == TokenType_Minus) { 97 | value.as_int = -value.as_int; 98 | } else { 99 | // TODO(voxel): Error Invalid operator 100 | } 101 | } else { 102 | // TODO(voxel): Error Invalid type 103 | } 104 | return value; 105 | } 106 | 107 | static void VM_Print(VM_RuntimeValue value) { 108 | switch (value.type) { 109 | case RuntimeValueType_Integer: { 110 | printf("Int32 %d\n", value.as_int); 111 | } break; 112 | 113 | default:; // TODO(voxel): Error Invalid type 114 | } 115 | } 116 | 117 | #define PushValue() dstack_push(VM_RuntimeValue, &datastack, *(VM_RuntimeValue*)&chunk->elems[i]) 118 | #define ReadOp() (*(L_TokenType*)&chunk->elems[i]) 119 | VM_RuntimeValue VM_RunExprChunk(IR_Chunk* chunk) { 120 | dstack(VM_RuntimeValue) datastack = {0}; 121 | 122 | u32 i = 0; 123 | while (i < chunk->len) { 124 | switch (chunk->elems[i]) { 125 | case Opcode_Nop: i++; break; 126 | case Opcode_Push: { 127 | i++; 128 | PushValue(); 129 | i += sizeof(VM_RuntimeValue); 130 | } break; 131 | 132 | case Opcode_Pop: { 133 | i++; 134 | dstack_pop(VM_RuntimeValue, &datastack); 135 | } break; 136 | 137 | case Opcode_UnaryOp: { 138 | i++; 139 | L_TokenType op = ReadOp(); 140 | i += sizeof(L_TokenType); 141 | VM_RuntimeValue v = dstack_pop(VM_RuntimeValue, &datastack); 142 | v = VM_UnaryOp(v, op); 143 | dstack_push(VM_RuntimeValue, &datastack, v); 144 | } break; 145 | 146 | case Opcode_BinaryOp: { 147 | i++; 148 | L_TokenType op = ReadOp(); 149 | i += sizeof(L_TokenType); 150 | VM_RuntimeValue v2 = dstack_pop(VM_RuntimeValue, &datastack); 151 | VM_RuntimeValue v1 = dstack_pop(VM_RuntimeValue, &datastack); 152 | v1 = VM_BinaryOp(v1, v2, op); 153 | dstack_push(VM_RuntimeValue, &datastack, v1); 154 | } break; 155 | 156 | case Opcode_Print: { 157 | i++; 158 | VM_RuntimeValue value = dstack_pop(VM_RuntimeValue, &datastack); 159 | VM_Print(value); 160 | } break; 161 | } 162 | } 163 | } 164 | #undef PushValue -------------------------------------------------------------------------------- /source/llvm_emitter.c: -------------------------------------------------------------------------------- 1 | #include "llvm_emitter.h" 2 | 3 | #include "llvm-c/Analysis.h" 4 | #include "llvm-c/Target.h" 5 | #include "llvm-c/TargetMachine.h" 6 | #include "llvm-c/Error.h" 7 | 8 | //~ Helpers 9 | 10 | static void LLVM_Report_LLVMHandler(const char* reason) { fprintf(stderr, "LLVM Error %s", reason); } 11 | 12 | //~ Code emission 13 | 14 | static LLVMValueRef LLVM_EmitUnary(LLVM_Emitter* emitter, L_TokenType op, LLVMValueRef operand) { 15 | switch (op) { 16 | case TokenType_Plus: return operand; 17 | case TokenType_Minus: return LLVMBuildNeg(emitter->builder, operand, ""); 18 | 19 | default: unreachable; 20 | } 21 | 22 | return (LLVMValueRef) {0}; 23 | } 24 | 25 | static LLVMValueRef LLVM_EmitBinary(LLVM_Emitter* emitter, L_TokenType op, LLVMValueRef a, LLVMValueRef b) { 26 | switch (op) { 27 | case TokenType_Plus: return LLVMBuildAdd(emitter->builder, a, b, ""); 28 | case TokenType_Minus: return LLVMBuildSub(emitter->builder, a, b, ""); 29 | case TokenType_Star: return LLVMBuildMul(emitter->builder, a, b, ""); 30 | case TokenType_Slash: return LLVMBuildUDiv(emitter->builder, a, b, ""); 31 | case TokenType_Percent: return LLVMBuildURem(emitter->builder, a, b, ""); 32 | 33 | default: unreachable; 34 | } 35 | return (LLVMValueRef) {0}; 36 | } 37 | 38 | 39 | LLVMValueRef LLVM_Emit(LLVM_Emitter* emitter, IR_Ast* ast) { 40 | switch (ast->type) { 41 | case AstType_IntLiteral: { 42 | return LLVMConstInt(emitter->int_32_type, ast->int_lit.value, false); 43 | } break; 44 | 45 | case AstType_FloatLiteral: { 46 | // TODO(voxel): 47 | } break; 48 | 49 | case AstType_ExprUnary: { 50 | LLVMValueRef operand = LLVM_Emit(emitter, ast->unary.operand); 51 | return LLVM_EmitUnary(emitter, ast->unary.operator.type, operand); 52 | } break; 53 | 54 | case AstType_ExprBinary: { 55 | LLVMValueRef a = LLVM_Emit(emitter, ast->binary.a); 56 | LLVMValueRef b = LLVM_Emit(emitter, ast->binary.b); 57 | return LLVM_EmitBinary(emitter, ast->binary.operator.type, a, b); 58 | } break; 59 | 60 | case AstType_StmtPrint: { 61 | // NOTE(voxel): Very Hardcoded ATM 62 | 63 | LLVMValueRef args[2] = { 64 | LLVMBuildPointerCast(emitter->builder, // cast [14 x i8] type to int8 pointer 65 | LLVMBuildGlobalString(emitter->builder, "%d", ""), 66 | emitter->int_8_type_ptr, ""), 67 | LLVM_Emit(emitter, ast->print.value), 68 | }; 69 | 70 | return LLVMBuildCall2(emitter->builder, emitter->printf_type, emitter->printf_object, args, 2, ""); 71 | } break; 72 | } 73 | 74 | return (LLVMValueRef) {0}; 75 | } 76 | 77 | //~ Init/Free 78 | 79 | #define INITIALIZE_TARGET(X) do { \ 80 | LLVMInitialize ## X ## AsmParser(); \ 81 | LLVMInitialize ## X ## AsmPrinter(); \ 82 | LLVMInitialize ## X ## TargetInfo(); \ 83 | LLVMInitialize ## X ## Target(); \ 84 | LLVMInitialize ## X ## Disassembler(); \ 85 | LLVMInitialize ## X ## TargetMC(); \ 86 | } while(0) 87 | 88 | void LLVM_Init(LLVM_Emitter* emitter) { 89 | MemoryZeroStruct(emitter, LLVM_Emitter); 90 | 91 | INITIALIZE_TARGET(X86); 92 | 93 | emitter->context = LLVMContextCreate(); 94 | emitter->module = LLVMModuleCreateWithNameInContext("Testing", emitter->context); 95 | emitter->builder = LLVMCreateBuilderInContext(emitter->context); 96 | 97 | LLVMTargetRef target; 98 | char* error = nullptr; 99 | if (LLVMGetTargetFromTriple(LLVMGetDefaultTargetTriple(), &target, &error) != 0) { 100 | printf("Target From Triple: %s\n", error); 101 | flush; 102 | } 103 | LLVMSetTarget(emitter->module, LLVMGetDefaultTargetTriple()); 104 | LLVMTargetMachineRef target_machine = LLVMCreateTargetMachine(target, LLVMGetDefaultTargetTriple(), "", "", LLVMCodeGenLevelNone, LLVMRelocDefault, LLVMCodeModelDefault); 105 | LLVMTargetDataRef target_data = LLVMCreateTargetDataLayout(target_machine); 106 | LLVMSetModuleDataLayout(emitter->module, target_data); 107 | 108 | LLVMInstallFatalErrorHandler(LLVM_Report_LLVMHandler); 109 | LLVMEnablePrettyStackTrace(); 110 | 111 | emitter->int_8_type = LLVMInt8TypeInContext(emitter->context); 112 | emitter->int_8_type_ptr = LLVMPointerType(emitter->int_8_type, 0); 113 | emitter->int_32_type = LLVMInt32TypeInContext(emitter->context); 114 | 115 | LLVMTypeRef printf_params[] = { emitter->int_8_type_ptr }; 116 | emitter->printf_type = LLVMFunctionType(emitter->int_32_type, printf_params, 1, true); 117 | emitter->printf_object = LLVMAddFunction(emitter->module, "printf", emitter->printf_type); 118 | 119 | LLVMTypeRef main_function_type = LLVMFunctionType(emitter->int_32_type, nullptr, 0, false); 120 | LLVMValueRef main_function = LLVMAddFunction(emitter->module, "main", main_function_type); 121 | 122 | LLVMBasicBlockRef entry = LLVMAppendBasicBlockInContext(emitter->context, main_function, "entry"); 123 | LLVMPositionBuilderAtEnd(emitter->builder, entry); 124 | } 125 | 126 | void LLVM_Free(LLVM_Emitter* emitter) { 127 | LLVMBuildRet(emitter->builder, LLVMConstInt(emitter->int_32_type, 0, false)); 128 | 129 | char* error = nullptr; 130 | 131 | LLVMVerifyModule(emitter->module, LLVMPrintMessageAction, nullptr); 132 | 133 | LLVMPrintModuleToFile(emitter->module, "hello.ll", &error); 134 | if (error) { 135 | fprintf(stderr, "Print Module Error: %s\n", error); 136 | fflush(stderr); 137 | LLVMDisposeErrorMessage(error); 138 | } 139 | 140 | LLVMDisposeBuilder(emitter->builder); 141 | LLVMDisposeModule(emitter->module); 142 | LLVMContextDispose(emitter->context); 143 | } 144 | -------------------------------------------------------------------------------- /third-party/include/llvm-c/Disassembler.h: -------------------------------------------------------------------------------- 1 | /*===-- llvm-c/Disassembler.h - Disassembler Public C Interface ---*- C -*-===*\ 2 | |* *| 3 | |* Part of the LLVM Project, under the Apache License v2.0 with LLVM *| 4 | |* Exceptions. *| 5 | |* See https://llvm.org/LICENSE.txt for license information. *| 6 | |* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception *| 7 | |* *| 8 | |*===----------------------------------------------------------------------===*| 9 | |* *| 10 | |* This header provides a public interface to a disassembler library. *| 11 | |* LLVM provides an implementation of this interface. *| 12 | |* *| 13 | \*===----------------------------------------------------------------------===*/ 14 | 15 | #ifndef LLVM_C_DISASSEMBLER_H 16 | #define LLVM_C_DISASSEMBLER_H 17 | 18 | #include "llvm-c/DisassemblerTypes.h" 19 | #include "llvm-c/ExternC.h" 20 | 21 | /** 22 | * @defgroup LLVMCDisassembler Disassembler 23 | * @ingroup LLVMC 24 | * 25 | * @{ 26 | */ 27 | 28 | LLVM_C_EXTERN_C_BEGIN 29 | 30 | /** 31 | * Create a disassembler for the TripleName. Symbolic disassembly is supported 32 | * by passing a block of information in the DisInfo parameter and specifying the 33 | * TagType and callback functions as described above. These can all be passed 34 | * as NULL. If successful, this returns a disassembler context. If not, it 35 | * returns NULL. This function is equivalent to calling 36 | * LLVMCreateDisasmCPUFeatures() with an empty CPU name and feature set. 37 | */ 38 | LLVMDisasmContextRef LLVMCreateDisasm(const char *TripleName, void *DisInfo, 39 | int TagType, LLVMOpInfoCallback GetOpInfo, 40 | LLVMSymbolLookupCallback SymbolLookUp); 41 | 42 | /** 43 | * Create a disassembler for the TripleName and a specific CPU. Symbolic 44 | * disassembly is supported by passing a block of information in the DisInfo 45 | * parameter and specifying the TagType and callback functions as described 46 | * above. These can all be passed * as NULL. If successful, this returns a 47 | * disassembler context. If not, it returns NULL. This function is equivalent 48 | * to calling LLVMCreateDisasmCPUFeatures() with an empty feature set. 49 | */ 50 | LLVMDisasmContextRef LLVMCreateDisasmCPU(const char *Triple, const char *CPU, 51 | void *DisInfo, int TagType, 52 | LLVMOpInfoCallback GetOpInfo, 53 | LLVMSymbolLookupCallback SymbolLookUp); 54 | 55 | /** 56 | * Create a disassembler for the TripleName, a specific CPU and specific feature 57 | * string. Symbolic disassembly is supported by passing a block of information 58 | * in the DisInfo parameter and specifying the TagType and callback functions as 59 | * described above. These can all be passed * as NULL. If successful, this 60 | * returns a disassembler context. If not, it returns NULL. 61 | */ 62 | LLVMDisasmContextRef 63 | LLVMCreateDisasmCPUFeatures(const char *Triple, const char *CPU, 64 | const char *Features, void *DisInfo, int TagType, 65 | LLVMOpInfoCallback GetOpInfo, 66 | LLVMSymbolLookupCallback SymbolLookUp); 67 | 68 | /** 69 | * Set the disassembler's options. Returns 1 if it can set the Options and 0 70 | * otherwise. 71 | */ 72 | int LLVMSetDisasmOptions(LLVMDisasmContextRef DC, uint64_t Options); 73 | 74 | /* The option to produce marked up assembly. */ 75 | #define LLVMDisassembler_Option_UseMarkup 1 76 | /* The option to print immediates as hex. */ 77 | #define LLVMDisassembler_Option_PrintImmHex 2 78 | /* The option use the other assembler printer variant */ 79 | #define LLVMDisassembler_Option_AsmPrinterVariant 4 80 | /* The option to set comment on instructions */ 81 | #define LLVMDisassembler_Option_SetInstrComments 8 82 | /* The option to print latency information alongside instructions */ 83 | #define LLVMDisassembler_Option_PrintLatency 16 84 | 85 | /** 86 | * Dispose of a disassembler context. 87 | */ 88 | void LLVMDisasmDispose(LLVMDisasmContextRef DC); 89 | 90 | /** 91 | * Disassemble a single instruction using the disassembler context specified in 92 | * the parameter DC. The bytes of the instruction are specified in the 93 | * parameter Bytes, and contains at least BytesSize number of bytes. The 94 | * instruction is at the address specified by the PC parameter. If a valid 95 | * instruction can be disassembled, its string is returned indirectly in 96 | * OutString whose size is specified in the parameter OutStringSize. This 97 | * function returns the number of bytes in the instruction or zero if there was 98 | * no valid instruction. 99 | */ 100 | size_t LLVMDisasmInstruction(LLVMDisasmContextRef DC, uint8_t *Bytes, 101 | uint64_t BytesSize, uint64_t PC, 102 | char *OutString, size_t OutStringSize); 103 | 104 | /** 105 | * @} 106 | */ 107 | 108 | LLVM_C_EXTERN_C_END 109 | 110 | #endif /* LLVM_C_DISASSEMBLER_H */ 111 | -------------------------------------------------------------------------------- /third-party/include/llvm-c/Types.h: -------------------------------------------------------------------------------- 1 | /*===-- llvm-c/Support.h - C Interface Types declarations ---------*- C -*-===*\ 2 | |* *| 3 | |* Part of the LLVM Project, under the Apache License v2.0 with LLVM *| 4 | |* Exceptions. *| 5 | |* See https://llvm.org/LICENSE.txt for license information. *| 6 | |* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception *| 7 | |* *| 8 | |*===----------------------------------------------------------------------===*| 9 | |* *| 10 | |* This file defines types used by the C interface to LLVM. *| 11 | |* *| 12 | \*===----------------------------------------------------------------------===*/ 13 | 14 | #ifndef LLVM_C_TYPES_H 15 | #define LLVM_C_TYPES_H 16 | 17 | #include "llvm-c/DataTypes.h" 18 | #include "llvm-c/ExternC.h" 19 | 20 | LLVM_C_EXTERN_C_BEGIN 21 | 22 | /** 23 | * @defgroup LLVMCSupportTypes Types and Enumerations 24 | * 25 | * @{ 26 | */ 27 | 28 | typedef int LLVMBool; 29 | 30 | /* Opaque types. */ 31 | 32 | /** 33 | * LLVM uses a polymorphic type hierarchy which C cannot represent, therefore 34 | * parameters must be passed as base types. Despite the declared types, most 35 | * of the functions provided operate only on branches of the type hierarchy. 36 | * The declared parameter names are descriptive and specify which type is 37 | * required. Additionally, each type hierarchy is documented along with the 38 | * functions that operate upon it. For more detail, refer to LLVM's C++ code. 39 | * If in doubt, refer to Core.cpp, which performs parameter downcasts in the 40 | * form unwrap(Param). 41 | */ 42 | 43 | /** 44 | * Used to pass regions of memory through LLVM interfaces. 45 | * 46 | * @see llvm::MemoryBuffer 47 | */ 48 | typedef struct LLVMOpaqueMemoryBuffer *LLVMMemoryBufferRef; 49 | 50 | /** 51 | * The top-level container for all LLVM global data. See the LLVMContext class. 52 | */ 53 | typedef struct LLVMOpaqueContext *LLVMContextRef; 54 | 55 | /** 56 | * The top-level container for all other LLVM Intermediate Representation (IR) 57 | * objects. 58 | * 59 | * @see llvm::Module 60 | */ 61 | typedef struct LLVMOpaqueModule *LLVMModuleRef; 62 | 63 | /** 64 | * Each value in the LLVM IR has a type, an LLVMTypeRef. 65 | * 66 | * @see llvm::Type 67 | */ 68 | typedef struct LLVMOpaqueType *LLVMTypeRef; 69 | 70 | /** 71 | * Represents an individual value in LLVM IR. 72 | * 73 | * This models llvm::Value. 74 | */ 75 | typedef struct LLVMOpaqueValue *LLVMValueRef; 76 | 77 | /** 78 | * Represents a basic block of instructions in LLVM IR. 79 | * 80 | * This models llvm::BasicBlock. 81 | */ 82 | typedef struct LLVMOpaqueBasicBlock *LLVMBasicBlockRef; 83 | 84 | /** 85 | * Represents an LLVM Metadata. 86 | * 87 | * This models llvm::Metadata. 88 | */ 89 | typedef struct LLVMOpaqueMetadata *LLVMMetadataRef; 90 | 91 | /** 92 | * Represents an LLVM Named Metadata Node. 93 | * 94 | * This models llvm::NamedMDNode. 95 | */ 96 | typedef struct LLVMOpaqueNamedMDNode *LLVMNamedMDNodeRef; 97 | 98 | /** 99 | * Represents an entry in a Global Object's metadata attachments. 100 | * 101 | * This models std::pair 102 | */ 103 | typedef struct LLVMOpaqueValueMetadataEntry LLVMValueMetadataEntry; 104 | 105 | /** 106 | * Represents an LLVM basic block builder. 107 | * 108 | * This models llvm::IRBuilder. 109 | */ 110 | typedef struct LLVMOpaqueBuilder *LLVMBuilderRef; 111 | 112 | /** 113 | * Represents an LLVM debug info builder. 114 | * 115 | * This models llvm::DIBuilder. 116 | */ 117 | typedef struct LLVMOpaqueDIBuilder *LLVMDIBuilderRef; 118 | 119 | /** 120 | * Interface used to provide a module to JIT or interpreter. 121 | * This is now just a synonym for llvm::Module, but we have to keep using the 122 | * different type to keep binary compatibility. 123 | */ 124 | typedef struct LLVMOpaqueModuleProvider *LLVMModuleProviderRef; 125 | 126 | /** @see llvm::PassManagerBase */ 127 | typedef struct LLVMOpaquePassManager *LLVMPassManagerRef; 128 | 129 | /** @see llvm::PassRegistry */ 130 | typedef struct LLVMOpaquePassRegistry *LLVMPassRegistryRef; 131 | 132 | /** 133 | * Used to get the users and usees of a Value. 134 | * 135 | * @see llvm::Use */ 136 | typedef struct LLVMOpaqueUse *LLVMUseRef; 137 | 138 | /** 139 | * Used to represent an attributes. 140 | * 141 | * @see llvm::Attribute 142 | */ 143 | typedef struct LLVMOpaqueAttributeRef *LLVMAttributeRef; 144 | 145 | /** 146 | * @see llvm::DiagnosticInfo 147 | */ 148 | typedef struct LLVMOpaqueDiagnosticInfo *LLVMDiagnosticInfoRef; 149 | 150 | /** 151 | * @see llvm::Comdat 152 | */ 153 | typedef struct LLVMComdat *LLVMComdatRef; 154 | 155 | /** 156 | * @see llvm::Module::ModuleFlagEntry 157 | */ 158 | typedef struct LLVMOpaqueModuleFlagEntry LLVMModuleFlagEntry; 159 | 160 | /** 161 | * @see llvm::JITEventListener 162 | */ 163 | typedef struct LLVMOpaqueJITEventListener *LLVMJITEventListenerRef; 164 | 165 | /** 166 | * @see llvm::object::Binary 167 | */ 168 | typedef struct LLVMOpaqueBinary *LLVMBinaryRef; 169 | 170 | /** 171 | * @} 172 | */ 173 | 174 | LLVM_C_EXTERN_C_END 175 | 176 | #endif 177 | -------------------------------------------------------------------------------- /source/parser.c: -------------------------------------------------------------------------------- 1 | #include "parser.h" 2 | 3 | #include 4 | 5 | #include "base/log.h" 6 | 7 | //~ Data 8 | 9 | u32 infix_expr_precs[] = { 10 | [TokenType_Star] = Prec_Factor, 11 | [TokenType_Slash] = Prec_Factor, 12 | 13 | [TokenType_Plus] = Prec_Term, 14 | [TokenType_Minus] = Prec_Term, 15 | 16 | [TokenType_TokenTypeCount] = Prec_Invalid, 17 | }; 18 | 19 | //~ Error Handling 20 | 21 | static void ErrorHere(P_Parser* p, const char* error, ...) { 22 | printf("Parser error: "); 23 | 24 | va_list va; 25 | va_start(va, error); 26 | vprintf(error, va); 27 | va_end(va); 28 | 29 | printf("\n"); 30 | } 31 | 32 | //~ Helpers 33 | 34 | static void Advance(P_Parser* p) { 35 | p->prev = p->curr; 36 | p->curr = p->next; 37 | p->next = L_LexToken(p->lexer); 38 | } 39 | 40 | static void EatOrError(P_Parser* p, L_TokenType type) { 41 | if (p->curr.type != type) 42 | ErrorHere(p, "Expected token %.*s but got %.*s", str_expand(L_GetTypeName(type)), str_expand(L_GetTypeName(p->next.type))); 43 | 44 | // Panic mode reset delimiters 45 | if (type == TokenType_Semicolon || 46 | type == TokenType_CloseBrace || 47 | type == TokenType_CloseParenthesis) 48 | p->panic_mode = false; 49 | Advance(p); 50 | } 51 | 52 | static b8 Match(P_Parser* p, L_TokenType type) { 53 | if (p->curr.type == type) { 54 | Advance(p); 55 | return true; 56 | } 57 | return false; 58 | } 59 | 60 | //~ Ast Allocators 61 | 62 | static IR_Ast* P_MakeIntLiteralNode(P_Parser* p, i32 value) { 63 | IR_Ast* ret = pool_alloc(p->ast_node_pool); 64 | ret->type = AstType_IntLiteral; 65 | ret->int_lit.value = value; 66 | return ret; 67 | } 68 | 69 | static IR_Ast* P_MakeFloatLiteralNode(P_Parser* p, f32 value) { 70 | IR_Ast* ret = pool_alloc(p->ast_node_pool); 71 | ret->type = AstType_FloatLiteral; 72 | ret->float_lit.value = value; 73 | return ret; 74 | } 75 | 76 | static IR_Ast* P_MakeExprUnaryNode(P_Parser* p, L_Token operator, IR_Ast* operand) { 77 | IR_Ast* ret = pool_alloc(p->ast_node_pool); 78 | ret->type = AstType_ExprUnary; 79 | ret->unary.operator = operator; 80 | ret->unary.operand = operand; 81 | return ret; 82 | } 83 | 84 | static IR_Ast* P_MakeExprBinaryNode(P_Parser* p, IR_Ast* a, L_Token operator, IR_Ast* b) { 85 | IR_Ast* ret = pool_alloc(p->ast_node_pool); 86 | ret->type = AstType_ExprBinary; 87 | ret->binary.operator = operator; 88 | ret->binary.a = a; 89 | ret->binary.b = b; 90 | return ret; 91 | } 92 | 93 | 94 | static IR_Ast* P_MakeStmtPrintNode(P_Parser* p, IR_Ast* value) { 95 | IR_Ast* ret = pool_alloc(p->ast_node_pool); 96 | ret->type = AstType_StmtPrint; 97 | ret->print.value = value; 98 | return ret; 99 | } 100 | 101 | //~ Parsing 102 | 103 | IR_Ast* P_ParseExpr(P_Parser* p, P_Precedence prec); 104 | IR_Ast* P_ParseStmt(P_Parser* p); 105 | IR_Ast* P_ParsePrefixExpr(P_Parser* p); 106 | 107 | IR_Ast* P_ParsePrefixUnaryExpr(P_Parser* p) { 108 | Advance(p); 109 | L_Token operator = p->curr; 110 | return P_MakeExprUnaryNode(p, operator, P_ParsePrefixExpr(p)); 111 | } 112 | 113 | IR_Ast* P_ParsePrefixExpr(P_Parser* p) { 114 | switch (p->curr.type) { 115 | case TokenType_IntLit: { 116 | Advance(p); 117 | i32 val = (i32) atoi((const char*)p->prev.lexeme.str); 118 | return P_MakeIntLiteralNode(p, val); 119 | } break; 120 | 121 | case TokenType_Plus: 122 | case TokenType_Minus: { 123 | return P_ParsePrefixUnaryExpr(p); 124 | } break; 125 | 126 | case TokenType_OpenParenthesis: { 127 | Advance(p); 128 | IR_Ast* in = P_ParseExpr(p, Prec_Invalid); 129 | EatOrError(p, TokenType_CloseParenthesis); 130 | return in; 131 | } 132 | 133 | default: { 134 | ErrorHere(p, "Unexpected token %.*s", str_expand(p->curr.lexeme)); 135 | } break; 136 | } 137 | return 0; 138 | } 139 | 140 | 141 | IR_Ast* P_ParseInfixExpr(P_Parser* p, L_Token op, P_Precedence prec, IR_Ast* left) { 142 | switch (op.type) { 143 | case TokenType_Plus: 144 | case TokenType_Minus: 145 | case TokenType_Star: 146 | case TokenType_Slash: 147 | case TokenType_Percent: { 148 | IR_Ast* right = P_ParseExpr(p, prec); 149 | return P_MakeExprBinaryNode(p, left, op, right); 150 | } break; 151 | 152 | default: { 153 | ErrorHere(p, "Unexpected token %.*s", str_expand(p->curr.lexeme)); 154 | } break; 155 | } 156 | return 0; 157 | } 158 | 159 | IR_Ast* P_ParseExpr(P_Parser* p, P_Precedence prec) { 160 | IR_Ast* lhs = P_ParsePrefixExpr(p); 161 | 162 | if (infix_expr_precs[p->curr.type] != Prec_Invalid) { 163 | Advance(p); 164 | L_Token op = p->prev; 165 | while (true) { 166 | if (infix_expr_precs[op.type] == Prec_Invalid) break; 167 | 168 | if (infix_expr_precs[op.type] >= prec) { 169 | lhs = P_ParseInfixExpr(p, op, infix_expr_precs[op.type] + 1, lhs); 170 | op = p->curr; 171 | 172 | if (infix_expr_precs[op.type] != Prec_Invalid) Advance(p); 173 | } else break; 174 | } 175 | } 176 | 177 | return lhs; 178 | } 179 | 180 | IR_Ast* P_ParseStmt(P_Parser* p) { 181 | if (Match(p, TokenType_Print)) { 182 | return P_MakeStmtPrintNode(p, P_ParseExpr(p, Prec_Invalid)); 183 | } 184 | 185 | ErrorHere(p, "Invalid Token for statement start"); 186 | return 0; 187 | } 188 | 189 | IR_Ast* P_Parse(P_Parser* p) { 190 | return P_ParseStmt(p); 191 | } 192 | 193 | //~ Lifecycle 194 | 195 | void P_Init(P_Parser* p, L_Lexer* lexer) { 196 | MemoryZeroStruct(p, P_Parser); 197 | 198 | p->lexer = lexer; 199 | p->ast_node_pool = pool_make(sizeof(IR_Ast)); 200 | 201 | Advance(p); 202 | Advance(p); 203 | } 204 | 205 | void P_Free(P_Parser* p) { 206 | pool_free(p->ast_node_pool); 207 | } 208 | -------------------------------------------------------------------------------- /source/base/vmath.h: -------------------------------------------------------------------------------- 1 | /* date = September 29th 2021 10:03 am */ 2 | 3 | #ifndef VMATH_H 4 | #define VMATH_H 5 | 6 | #include "defines.h" 7 | #include 8 | 9 | #define EPSILON 0.001f 10 | #define PI 3.141592653589f 11 | #define PHI 1.61803399f 12 | #define HALF_PI 1.570796326794f 13 | #define DEG_TO_RAD 0.0174532925f 14 | #define RAD_TO_DEG 57.2957795131 15 | #define FLOAT_MAX 340282346638528859811704183484516925440.0000000000000000 16 | #define FLOAT_MIN -FLOAT_MAX 17 | 18 | #define Color_Red vec4_init(0.8f, 0.3f, 0.2f, 1.f) 19 | #define Color_Green vec4_init(0.2f, 0.8f, 0.3f, 1.f) 20 | #define Color_Blue vec4_init(0.3f, 0.2f, 0.8f, 1.f) 21 | #define Color_Magenta vec4_init(0.8f, 0.3f, 0.7f, 1.f) 22 | #define Color_Cyan vec4_init(0.3f, 0.8f, 0.7f, 1.f) 23 | #define Color_Yellow vec4_init(0.8f, 0.7f, 0.3f, 1.f) 24 | #define Color_PureGreen vec4_init(0.0f, 1.0f, 0.0f, 1.f) 25 | #define Color_PureRed vec4_init(1.0f, 0.0f, 0.0f, 1.f) 26 | #define Color_PureBlue vec4_init(0.0f, 0.0f, 1.0f, 1.f) 27 | #define Color_White vec4_init(1.0f, 1.0f, 1.0f, 1.f) 28 | 29 | #define EpsilonEquals(x, y) ((fabs((x) - (y)) <= EPSILON) ? true : false) 30 | 31 | typedef struct vec2 { f32 x; f32 y; } vec2; 32 | typedef struct vec3 { f32 x; f32 y; f32 z; } vec3; 33 | typedef struct vec4 { f32 x; f32 y; f32 z; f32 w; } vec4; 34 | 35 | typedef struct mat3 { f32 a[3*3]; } mat3; 36 | typedef struct mat4 { f32 a[4*4]; } mat4; 37 | 38 | typedef struct rect { f32 x; f32 y; f32 w; f32 h; } rect; 39 | typedef struct quat { f32 s; f32 i; f32 j; f32 k; } quat; 40 | 41 | //~ Math Utilities 42 | 43 | void animate_f32exp(f32* val, f32 target, f32 speed, f32 dt); 44 | 45 | typedef u32 axis2; 46 | enum { 47 | axis2_x, 48 | axis2_y, 49 | axis2_count, 50 | }; 51 | 52 | typedef u32 axis3; 53 | enum { 54 | axis3_x, 55 | axis3_y, 56 | axis3_z, 57 | axis3_count, 58 | }; 59 | 60 | //~ Inline Initializers 61 | 62 | static inline vec2 vec2_init(f32 x, f32 y) { return (vec2) { x, y }; } 63 | static inline vec3 vec3_init(f32 x, f32 y, f32 z) { return (vec3) { x, y, z }; } 64 | static inline vec4 vec4_init(f32 x, f32 y, f32 z, f32 w) { return (vec4) { x, y, z, w }; } 65 | static inline rect rect_init(f32 x, f32 y, f32 w, f32 h) { return (rect) { x, y, w, h }; } 66 | static inline quat quat_init(f32 s, f32 i, f32 j, f32 k) { return (quat) { s, i, j, k }; } 67 | 68 | static inline u16 mat3_idx(u16 x, u16 y) { return y * 3 + x; } 69 | static inline u16 mat4_idx(u16 x, u16 y) { return y * 4 + x; } 70 | 71 | static inline f64 radians(f32 deg) { return (f64) (deg * DEG_TO_RAD); } 72 | static inline f32 degrees(f64 rad) { return (f32) (rad * RAD_TO_DEG); } 73 | 74 | //~ Vector Functions 75 | 76 | static inline vec2 vec2_add(vec2 a, vec2 b) { return (vec2) { .x = a.x + b.x, .y = a.y + b.y }; } 77 | static inline vec2 vec2_sub(vec2 a, vec2 b) { return (vec2) { .x = a.x - b.x, .y = a.y - b.y }; } 78 | static inline vec2 vec2_scale(vec2 a, f32 s) { return (vec2) { .x = a.x * s, .y = a.y * s }; } 79 | static inline f32 vec2_mag(vec2 v) { return sqrtf(v.x * v.x + v.y * v.y); } 80 | static inline f32 vec2_magsq(vec2 v) { return v.x * v.x + v.y * v.y; } 81 | static inline vec2 vec2_normalize(vec2 v) { return vec2_scale(v, 1.f / vec2_mag(v)); } 82 | static inline vec2 vec2_neg(vec2 v) { return (vec2) { .x = -v.x, .y = -v.y }; } 83 | static inline f32 vec2_dot(vec2 a, vec2 b) { return a.x * b.x + a.y * b.y; } 84 | vec2 vec2_triple_product(vec2 a, vec2 b, vec2 c); 85 | vec2 vec2_clamp(vec2 vec, rect quad); 86 | 87 | static inline 88 | vec3 vec3_add(vec3 a, vec3 b) { return (vec3) { .x = a.x + b.x, .y = a.y + b.y, .z = a.z + b.z }; } 89 | static inline 90 | vec3 vec3_sub(vec3 a, vec3 b) { return (vec3) { .x = a.x - b.x, .y = a.y - b.y, .z = a.z - b.z }; } 91 | static inline 92 | vec3 vec3_scale(vec3 a, f32 s) { return (vec3) { .x = a.x * s, .y = a.y * s, .z = a.z * s }; } 93 | static inline 94 | vec3 vec3_cross(vec3 a, vec3 b) { return (vec3) { .x = a.y * b.z - b.y * a.z, .y = a.x * b.z - b.x * a.z, .z = a.x * b.y + b.x * a.y }; } 95 | 96 | static inline 97 | vec4 vec4_add(vec4 a, vec4 b) { return (vec4) { .x = a.x + b.x, .y = a.y + b.y, .z = a.z + b.z, .w = a.w + b.w }; } 98 | static inline 99 | vec4 vec4_sub(vec4 a, vec4 b) { return (vec4) { .x = a.x - b.x, .y = a.y - b.y, .z = a.z - b.z, .w = a.w - b.w }; } 100 | static inline 101 | vec4 vec4_scale(vec4 a, f32 s) { return (vec4) { .x = a.x * s, .y = a.y * s, .z = a.z * s, .w = a.w * s }; } 102 | 103 | vec3 vec3_mul(vec3 a, mat3 m); 104 | vec4 vec4_mul(vec4 a, mat4 m); 105 | 106 | //~ Matrix Functions 107 | 108 | mat3 mat3_identity(); 109 | mat4 mat4_identity(); 110 | 111 | mat3 mat3_mul(mat3 a, mat3 b); 112 | void mat3_set(mat3* mat, mat3 o); 113 | 114 | mat3 mat3_translate(vec2 v); 115 | mat3 mat3_rotate(f32 r); 116 | mat3 mat3_scalev(vec2 s); 117 | mat3 mat3_scalef(f32 s); 118 | 119 | mat4 mat4_mul(mat4 a, mat4 b); 120 | void mat4_set(mat4* mat, mat4 o); 121 | mat4 mat4_transpose(mat4 a); 122 | 123 | mat4 mat4_translate(vec3 v); 124 | mat4 mat4_scale(vec3 v); 125 | mat4 mat4_rotX(f32 deg); 126 | mat4 mat4_rotY(f32 deg); 127 | mat4 mat4_rotZ(f32 deg); 128 | mat4 mat4_ortho(f32 left, f32 right, f32 top, f32 bottom, f32 near, f32 far); 129 | mat4 mat4_perspective(f32 fov, f32 aspect_ratio, f32 near, f32 far); 130 | 131 | //~ Quaternion Functions 132 | 133 | quat quat_identity(); 134 | 135 | quat quat_mul(quat a, quat b); 136 | f32 quat_length(quat q); 137 | quat quat_norm(quat q); 138 | quat quat_rotate_axis(quat q, f32 x, f32 y, f32 z, f32 a); 139 | quat quat_from_euler(f32 yaw, f32 pitch, f32 roll); 140 | mat4 quat_to_rotation_mat(quat q); 141 | 142 | //~ Rect Functions 143 | 144 | b8 rect_contains_point(rect a, vec2 p); 145 | b8 rect_overlaps(rect a, rect b); 146 | b8 rect_contained_by_rect(rect a, rect b); 147 | rect rect_get_overlap(rect a, rect b); 148 | rect rect_uv_cull(rect quad, rect uv, rect cull_quad); 149 | 150 | #endif //VMATH_H 151 | -------------------------------------------------------------------------------- /third-party/include/llvm-c/Transforms/Scalar.h: -------------------------------------------------------------------------------- 1 | /*===-- Scalar.h - Scalar Transformation Library C Interface ----*- C++ -*-===*\ 2 | |* *| 3 | |* Part of the LLVM Project, under the Apache License v2.0 with LLVM *| 4 | |* Exceptions. *| 5 | |* See https://llvm.org/LICENSE.txt for license information. *| 6 | |* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception *| 7 | |* *| 8 | |*===----------------------------------------------------------------------===*| 9 | |* *| 10 | |* This header declares the C interface to libLLVMScalarOpts.a, which *| 11 | |* implements various scalar transformations of the LLVM IR. *| 12 | |* *| 13 | |* Many exotic languages can interoperate with C code but have a harder time *| 14 | |* with C++ due to name mangling. So in addition to C, this interface enables *| 15 | |* tools written in such languages. *| 16 | |* *| 17 | \*===----------------------------------------------------------------------===*/ 18 | 19 | #ifndef LLVM_C_TRANSFORMS_SCALAR_H 20 | #define LLVM_C_TRANSFORMS_SCALAR_H 21 | 22 | #include "llvm-c/ExternC.h" 23 | #include "llvm-c/Types.h" 24 | 25 | LLVM_C_EXTERN_C_BEGIN 26 | 27 | /** 28 | * @defgroup LLVMCTransformsScalar Scalar transformations 29 | * @ingroup LLVMCTransforms 30 | * 31 | * @{ 32 | */ 33 | 34 | /** See llvm::createAggressiveDCEPass function. */ 35 | void LLVMAddAggressiveDCEPass(LLVMPassManagerRef PM); 36 | 37 | /** See llvm::createDeadCodeEliminationPass function. */ 38 | void LLVMAddDCEPass(LLVMPassManagerRef PM); 39 | 40 | /** See llvm::createBitTrackingDCEPass function. */ 41 | void LLVMAddBitTrackingDCEPass(LLVMPassManagerRef PM); 42 | 43 | /** See llvm::createAlignmentFromAssumptionsPass function. */ 44 | void LLVMAddAlignmentFromAssumptionsPass(LLVMPassManagerRef PM); 45 | 46 | /** See llvm::createCFGSimplificationPass function. */ 47 | void LLVMAddCFGSimplificationPass(LLVMPassManagerRef PM); 48 | 49 | /** See llvm::createDeadStoreEliminationPass function. */ 50 | void LLVMAddDeadStoreEliminationPass(LLVMPassManagerRef PM); 51 | 52 | /** See llvm::createScalarizerPass function. */ 53 | void LLVMAddScalarizerPass(LLVMPassManagerRef PM); 54 | 55 | /** See llvm::createMergedLoadStoreMotionPass function. */ 56 | void LLVMAddMergedLoadStoreMotionPass(LLVMPassManagerRef PM); 57 | 58 | /** See llvm::createGVNPass function. */ 59 | void LLVMAddGVNPass(LLVMPassManagerRef PM); 60 | 61 | /** See llvm::createGVNPass function. */ 62 | void LLVMAddNewGVNPass(LLVMPassManagerRef PM); 63 | 64 | /** See llvm::createIndVarSimplifyPass function. */ 65 | void LLVMAddIndVarSimplifyPass(LLVMPassManagerRef PM); 66 | 67 | /** See llvm::createInstructionCombiningPass function. */ 68 | void LLVMAddInstructionCombiningPass(LLVMPassManagerRef PM); 69 | 70 | /** See llvm::createInstSimplifyLegacyPass function. */ 71 | void LLVMAddInstructionSimplifyPass(LLVMPassManagerRef PM); 72 | 73 | /** See llvm::createJumpThreadingPass function. */ 74 | void LLVMAddJumpThreadingPass(LLVMPassManagerRef PM); 75 | 76 | /** See llvm::createLICMPass function. */ 77 | void LLVMAddLICMPass(LLVMPassManagerRef PM); 78 | 79 | /** See llvm::createLoopDeletionPass function. */ 80 | void LLVMAddLoopDeletionPass(LLVMPassManagerRef PM); 81 | 82 | /** See llvm::createLoopIdiomPass function */ 83 | void LLVMAddLoopIdiomPass(LLVMPassManagerRef PM); 84 | 85 | /** See llvm::createLoopRotatePass function. */ 86 | void LLVMAddLoopRotatePass(LLVMPassManagerRef PM); 87 | 88 | /** See llvm::createLoopRerollPass function. */ 89 | void LLVMAddLoopRerollPass(LLVMPassManagerRef PM); 90 | 91 | /** See llvm::createLoopUnrollPass function. */ 92 | void LLVMAddLoopUnrollPass(LLVMPassManagerRef PM); 93 | 94 | /** See llvm::createLoopUnrollAndJamPass function. */ 95 | void LLVMAddLoopUnrollAndJamPass(LLVMPassManagerRef PM); 96 | 97 | /** See llvm::createLoopUnswitchPass function. */ 98 | void LLVMAddLoopUnswitchPass(LLVMPassManagerRef PM); 99 | 100 | /** See llvm::createLowerAtomicPass function. */ 101 | void LLVMAddLowerAtomicPass(LLVMPassManagerRef PM); 102 | 103 | /** See llvm::createMemCpyOptPass function. */ 104 | void LLVMAddMemCpyOptPass(LLVMPassManagerRef PM); 105 | 106 | /** See llvm::createPartiallyInlineLibCallsPass function. */ 107 | void LLVMAddPartiallyInlineLibCallsPass(LLVMPassManagerRef PM); 108 | 109 | /** See llvm::createReassociatePass function. */ 110 | void LLVMAddReassociatePass(LLVMPassManagerRef PM); 111 | 112 | /** See llvm::createSCCPPass function. */ 113 | void LLVMAddSCCPPass(LLVMPassManagerRef PM); 114 | 115 | /** See llvm::createSROAPass function. */ 116 | void LLVMAddScalarReplAggregatesPass(LLVMPassManagerRef PM); 117 | 118 | /** See llvm::createSROAPass function. */ 119 | void LLVMAddScalarReplAggregatesPassSSA(LLVMPassManagerRef PM); 120 | 121 | /** See llvm::createSROAPass function. */ 122 | void LLVMAddScalarReplAggregatesPassWithThreshold(LLVMPassManagerRef PM, 123 | int Threshold); 124 | 125 | /** See llvm::createSimplifyLibCallsPass function. */ 126 | void LLVMAddSimplifyLibCallsPass(LLVMPassManagerRef PM); 127 | 128 | /** See llvm::createTailCallEliminationPass function. */ 129 | void LLVMAddTailCallEliminationPass(LLVMPassManagerRef PM); 130 | 131 | /** See llvm::demotePromoteMemoryToRegisterPass function. */ 132 | void LLVMAddDemoteMemoryToRegisterPass(LLVMPassManagerRef PM); 133 | 134 | /** See llvm::createVerifierPass function. */ 135 | void LLVMAddVerifierPass(LLVMPassManagerRef PM); 136 | 137 | /** See llvm::createCorrelatedValuePropagationPass function */ 138 | void LLVMAddCorrelatedValuePropagationPass(LLVMPassManagerRef PM); 139 | 140 | /** See llvm::createEarlyCSEPass function */ 141 | void LLVMAddEarlyCSEPass(LLVMPassManagerRef PM); 142 | 143 | /** See llvm::createEarlyCSEPass function */ 144 | void LLVMAddEarlyCSEMemSSAPass(LLVMPassManagerRef PM); 145 | 146 | /** See llvm::createLowerExpectIntrinsicPass function */ 147 | void LLVMAddLowerExpectIntrinsicPass(LLVMPassManagerRef PM); 148 | 149 | /** See llvm::createLowerConstantIntrinsicsPass function */ 150 | void LLVMAddLowerConstantIntrinsicsPass(LLVMPassManagerRef PM); 151 | 152 | /** See llvm::createTypeBasedAliasAnalysisPass function */ 153 | void LLVMAddTypeBasedAliasAnalysisPass(LLVMPassManagerRef PM); 154 | 155 | /** See llvm::createScopedNoAliasAAPass function */ 156 | void LLVMAddScopedNoAliasAAPass(LLVMPassManagerRef PM); 157 | 158 | /** See llvm::createBasicAliasAnalysisPass function */ 159 | void LLVMAddBasicAliasAnalysisPass(LLVMPassManagerRef PM); 160 | 161 | /** See llvm::createUnifyFunctionExitNodesPass function */ 162 | void LLVMAddUnifyFunctionExitNodesPass(LLVMPassManagerRef PM); 163 | 164 | /** 165 | * @} 166 | */ 167 | 168 | LLVM_C_EXTERN_C_END 169 | 170 | #endif 171 | -------------------------------------------------------------------------------- /third-party/include/llvm-c/TargetMachine.h: -------------------------------------------------------------------------------- 1 | /*===-- llvm-c/TargetMachine.h - Target Machine Library C Interface - C++ -*-=*\ 2 | |* *| 3 | |* Part of the LLVM Project, under the Apache License v2.0 with LLVM *| 4 | |* Exceptions. *| 5 | |* See https://llvm.org/LICENSE.txt for license information. *| 6 | |* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception *| 7 | |* *| 8 | |*===----------------------------------------------------------------------===*| 9 | |* *| 10 | |* This header declares the C interface to the Target and TargetMachine *| 11 | |* classes, which can be used to generate assembly or object files. *| 12 | |* *| 13 | |* Many exotic languages can interoperate with C code but have a harder time *| 14 | |* with C++ due to name mangling. So in addition to C, this interface enables *| 15 | |* tools written in such languages. *| 16 | |* *| 17 | \*===----------------------------------------------------------------------===*/ 18 | 19 | #ifndef LLVM_C_TARGETMACHINE_H 20 | #define LLVM_C_TARGETMACHINE_H 21 | 22 | #include "llvm-c/ExternC.h" 23 | #include "llvm-c/Target.h" 24 | #include "llvm-c/Types.h" 25 | 26 | LLVM_C_EXTERN_C_BEGIN 27 | 28 | typedef struct LLVMOpaqueTargetMachine *LLVMTargetMachineRef; 29 | typedef struct LLVMTarget *LLVMTargetRef; 30 | 31 | typedef enum { 32 | LLVMCodeGenLevelNone, 33 | LLVMCodeGenLevelLess, 34 | LLVMCodeGenLevelDefault, 35 | LLVMCodeGenLevelAggressive 36 | } LLVMCodeGenOptLevel; 37 | 38 | typedef enum { 39 | LLVMRelocDefault, 40 | LLVMRelocStatic, 41 | LLVMRelocPIC, 42 | LLVMRelocDynamicNoPic, 43 | LLVMRelocROPI, 44 | LLVMRelocRWPI, 45 | LLVMRelocROPI_RWPI 46 | } LLVMRelocMode; 47 | 48 | typedef enum { 49 | LLVMCodeModelDefault, 50 | LLVMCodeModelJITDefault, 51 | LLVMCodeModelTiny, 52 | LLVMCodeModelSmall, 53 | LLVMCodeModelKernel, 54 | LLVMCodeModelMedium, 55 | LLVMCodeModelLarge 56 | } LLVMCodeModel; 57 | 58 | typedef enum { 59 | LLVMAssemblyFile, 60 | LLVMObjectFile 61 | } LLVMCodeGenFileType; 62 | 63 | /** Returns the first llvm::Target in the registered targets list. */ 64 | LLVMTargetRef LLVMGetFirstTarget(void); 65 | /** Returns the next llvm::Target given a previous one (or null if there's none) */ 66 | LLVMTargetRef LLVMGetNextTarget(LLVMTargetRef T); 67 | 68 | /*===-- Target ------------------------------------------------------------===*/ 69 | /** Finds the target corresponding to the given name and stores it in \p T. 70 | Returns 0 on success. */ 71 | LLVMTargetRef LLVMGetTargetFromName(const char *Name); 72 | 73 | /** Finds the target corresponding to the given triple and stores it in \p T. 74 | Returns 0 on success. Optionally returns any error in ErrorMessage. 75 | Use LLVMDisposeMessage to dispose the message. */ 76 | LLVMBool LLVMGetTargetFromTriple(const char* Triple, LLVMTargetRef *T, 77 | char **ErrorMessage); 78 | 79 | /** Returns the name of a target. See llvm::Target::getName */ 80 | const char *LLVMGetTargetName(LLVMTargetRef T); 81 | 82 | /** Returns the description of a target. See llvm::Target::getDescription */ 83 | const char *LLVMGetTargetDescription(LLVMTargetRef T); 84 | 85 | /** Returns if the target has a JIT */ 86 | LLVMBool LLVMTargetHasJIT(LLVMTargetRef T); 87 | 88 | /** Returns if the target has a TargetMachine associated */ 89 | LLVMBool LLVMTargetHasTargetMachine(LLVMTargetRef T); 90 | 91 | /** Returns if the target as an ASM backend (required for emitting output) */ 92 | LLVMBool LLVMTargetHasAsmBackend(LLVMTargetRef T); 93 | 94 | /*===-- Target Machine ----------------------------------------------------===*/ 95 | /** Creates a new llvm::TargetMachine. See llvm::Target::createTargetMachine */ 96 | LLVMTargetMachineRef LLVMCreateTargetMachine(LLVMTargetRef T, 97 | const char *Triple, const char *CPU, const char *Features, 98 | LLVMCodeGenOptLevel Level, LLVMRelocMode Reloc, LLVMCodeModel CodeModel); 99 | 100 | /** Dispose the LLVMTargetMachineRef instance generated by 101 | LLVMCreateTargetMachine. */ 102 | void LLVMDisposeTargetMachine(LLVMTargetMachineRef T); 103 | 104 | /** Returns the Target used in a TargetMachine */ 105 | LLVMTargetRef LLVMGetTargetMachineTarget(LLVMTargetMachineRef T); 106 | 107 | /** Returns the triple used creating this target machine. See 108 | llvm::TargetMachine::getTriple. The result needs to be disposed with 109 | LLVMDisposeMessage. */ 110 | char *LLVMGetTargetMachineTriple(LLVMTargetMachineRef T); 111 | 112 | /** Returns the cpu used creating this target machine. See 113 | llvm::TargetMachine::getCPU. The result needs to be disposed with 114 | LLVMDisposeMessage. */ 115 | char *LLVMGetTargetMachineCPU(LLVMTargetMachineRef T); 116 | 117 | /** Returns the feature string used creating this target machine. See 118 | llvm::TargetMachine::getFeatureString. The result needs to be disposed with 119 | LLVMDisposeMessage. */ 120 | char *LLVMGetTargetMachineFeatureString(LLVMTargetMachineRef T); 121 | 122 | /** Create a DataLayout based on the targetMachine. */ 123 | LLVMTargetDataRef LLVMCreateTargetDataLayout(LLVMTargetMachineRef T); 124 | 125 | /** Set the target machine's ASM verbosity. */ 126 | void LLVMSetTargetMachineAsmVerbosity(LLVMTargetMachineRef T, 127 | LLVMBool VerboseAsm); 128 | 129 | /** Emits an asm or object file for the given module to the filename. This 130 | wraps several c++ only classes (among them a file stream). Returns any 131 | error in ErrorMessage. Use LLVMDisposeMessage to dispose the message. */ 132 | LLVMBool LLVMTargetMachineEmitToFile(LLVMTargetMachineRef T, LLVMModuleRef M, 133 | char *Filename, LLVMCodeGenFileType codegen, char **ErrorMessage); 134 | 135 | /** Compile the LLVM IR stored in \p M and store the result in \p OutMemBuf. */ 136 | LLVMBool LLVMTargetMachineEmitToMemoryBuffer(LLVMTargetMachineRef T, LLVMModuleRef M, 137 | LLVMCodeGenFileType codegen, char** ErrorMessage, LLVMMemoryBufferRef *OutMemBuf); 138 | 139 | /*===-- Triple ------------------------------------------------------------===*/ 140 | /** Get a triple for the host machine as a string. The result needs to be 141 | disposed with LLVMDisposeMessage. */ 142 | char* LLVMGetDefaultTargetTriple(void); 143 | 144 | /** Normalize a target triple. The result needs to be disposed with 145 | LLVMDisposeMessage. */ 146 | char* LLVMNormalizeTargetTriple(const char* triple); 147 | 148 | /** Get the host CPU as a string. The result needs to be disposed with 149 | LLVMDisposeMessage. */ 150 | char* LLVMGetHostCPUName(void); 151 | 152 | /** Get the host CPU's features as a string. The result needs to be disposed 153 | with LLVMDisposeMessage. */ 154 | char* LLVMGetHostCPUFeatures(void); 155 | 156 | /** Adds the target-specific analysis passes to the pass manager. */ 157 | void LLVMAddAnalysisPasses(LLVMTargetMachineRef T, LLVMPassManagerRef PM); 158 | 159 | LLVM_C_EXTERN_C_END 160 | 161 | #endif 162 | -------------------------------------------------------------------------------- /third-party/include/llvm-c/DisassemblerTypes.h: -------------------------------------------------------------------------------- 1 | /*===-- llvm-c/DisassemblerTypedefs.h -----------------------------*- C -*-===*\ 2 | |* *| 3 | |* Part of the LLVM Project, under the Apache License v2.0 with LLVM *| 4 | |* Exceptions. *| 5 | |* See https://llvm.org/LICENSE.txt for license information. *| 6 | |* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception *| 7 | |* *| 8 | |*===----------------------------------------------------------------------===*/ 9 | 10 | #ifndef LLVM_C_DISASSEMBLERTYPES_H 11 | #define LLVM_C_DISASSEMBLERTYPES_H 12 | 13 | #include "llvm-c/DataTypes.h" 14 | #ifdef __cplusplus 15 | #include 16 | #else 17 | #include 18 | #endif 19 | 20 | /** 21 | * An opaque reference to a disassembler context. 22 | */ 23 | typedef void *LLVMDisasmContextRef; 24 | 25 | /** 26 | * The type for the operand information call back function. This is called to 27 | * get the symbolic information for an operand of an instruction. Typically 28 | * this is from the relocation information, symbol table, etc. That block of 29 | * information is saved when the disassembler context is created and passed to 30 | * the call back in the DisInfo parameter. The instruction containing operand 31 | * is at the PC parameter. For some instruction sets, there can be more than 32 | * one operand with symbolic information. To determine the symbolic operand 33 | * information for each operand, the bytes for the specific operand in the 34 | * instruction are specified by the Offset parameter and its byte widith is the 35 | * size parameter. For instructions sets with fixed widths and one symbolic 36 | * operand per instruction, the Offset parameter will be zero and Size parameter 37 | * will be the instruction width. The information is returned in TagBuf and is 38 | * Triple specific with its specific information defined by the value of 39 | * TagType for that Triple. If symbolic information is returned the function 40 | * returns 1, otherwise it returns 0. 41 | */ 42 | typedef int (*LLVMOpInfoCallback)(void *DisInfo, uint64_t PC, 43 | uint64_t Offset, uint64_t Size, 44 | int TagType, void *TagBuf); 45 | 46 | /** 47 | * The initial support in LLVM MC for the most general form of a relocatable 48 | * expression is "AddSymbol - SubtractSymbol + Offset". For some Darwin targets 49 | * this full form is encoded in the relocation information so that AddSymbol and 50 | * SubtractSymbol can be link edited independent of each other. Many other 51 | * platforms only allow a relocatable expression of the form AddSymbol + Offset 52 | * to be encoded. 53 | * 54 | * The LLVMOpInfoCallback() for the TagType value of 1 uses the struct 55 | * LLVMOpInfo1. The value of the relocatable expression for the operand, 56 | * including any PC adjustment, is passed in to the call back in the Value 57 | * field. The symbolic information about the operand is returned using all 58 | * the fields of the structure with the Offset of the relocatable expression 59 | * returned in the Value field. It is possible that some symbols in the 60 | * relocatable expression were assembly temporary symbols, for example 61 | * "Ldata - LpicBase + constant", and only the Values of the symbols without 62 | * symbol names are present in the relocation information. The VariantKind 63 | * type is one of the Target specific #defines below and is used to print 64 | * operands like "_foo@GOT", ":lower16:_foo", etc. 65 | */ 66 | struct LLVMOpInfoSymbol1 { 67 | uint64_t Present; /* 1 if this symbol is present */ 68 | const char *Name; /* symbol name if not NULL */ 69 | uint64_t Value; /* symbol value if name is NULL */ 70 | }; 71 | 72 | struct LLVMOpInfo1 { 73 | struct LLVMOpInfoSymbol1 AddSymbol; 74 | struct LLVMOpInfoSymbol1 SubtractSymbol; 75 | uint64_t Value; 76 | uint64_t VariantKind; 77 | }; 78 | 79 | /** 80 | * The operand VariantKinds for symbolic disassembly. 81 | */ 82 | #define LLVMDisassembler_VariantKind_None 0 /* all targets */ 83 | 84 | /** 85 | * The ARM target VariantKinds. 86 | */ 87 | #define LLVMDisassembler_VariantKind_ARM_HI16 1 /* :upper16: */ 88 | #define LLVMDisassembler_VariantKind_ARM_LO16 2 /* :lower16: */ 89 | 90 | /** 91 | * The ARM64 target VariantKinds. 92 | */ 93 | #define LLVMDisassembler_VariantKind_ARM64_PAGE 1 /* @page */ 94 | #define LLVMDisassembler_VariantKind_ARM64_PAGEOFF 2 /* @pageoff */ 95 | #define LLVMDisassembler_VariantKind_ARM64_GOTPAGE 3 /* @gotpage */ 96 | #define LLVMDisassembler_VariantKind_ARM64_GOTPAGEOFF 4 /* @gotpageoff */ 97 | #define LLVMDisassembler_VariantKind_ARM64_TLVP 5 /* @tvlppage */ 98 | #define LLVMDisassembler_VariantKind_ARM64_TLVOFF 6 /* @tvlppageoff */ 99 | 100 | /** 101 | * The type for the symbol lookup function. This may be called by the 102 | * disassembler for things like adding a comment for a PC plus a constant 103 | * offset load instruction to use a symbol name instead of a load address value. 104 | * It is passed the block information is saved when the disassembler context is 105 | * created and the ReferenceValue to look up as a symbol. If no symbol is found 106 | * for the ReferenceValue NULL is returned. The ReferenceType of the 107 | * instruction is passed indirectly as is the PC of the instruction in 108 | * ReferencePC. If the output reference can be determined its type is returned 109 | * indirectly in ReferenceType along with ReferenceName if any, or that is set 110 | * to NULL. 111 | */ 112 | typedef const char *(*LLVMSymbolLookupCallback)(void *DisInfo, 113 | uint64_t ReferenceValue, 114 | uint64_t *ReferenceType, 115 | uint64_t ReferencePC, 116 | const char **ReferenceName); 117 | /** 118 | * The reference types on input and output. 119 | */ 120 | /* No input reference type or no output reference type. */ 121 | #define LLVMDisassembler_ReferenceType_InOut_None 0 122 | 123 | /* The input reference is from a branch instruction. */ 124 | #define LLVMDisassembler_ReferenceType_In_Branch 1 125 | /* The input reference is from a PC relative load instruction. */ 126 | #define LLVMDisassembler_ReferenceType_In_PCrel_Load 2 127 | 128 | /* The input reference is from an ARM64::ADRP instruction. */ 129 | #define LLVMDisassembler_ReferenceType_In_ARM64_ADRP 0x100000001 130 | /* The input reference is from an ARM64::ADDXri instruction. */ 131 | #define LLVMDisassembler_ReferenceType_In_ARM64_ADDXri 0x100000002 132 | /* The input reference is from an ARM64::LDRXui instruction. */ 133 | #define LLVMDisassembler_ReferenceType_In_ARM64_LDRXui 0x100000003 134 | /* The input reference is from an ARM64::LDRXl instruction. */ 135 | #define LLVMDisassembler_ReferenceType_In_ARM64_LDRXl 0x100000004 136 | /* The input reference is from an ARM64::ADR instruction. */ 137 | #define LLVMDisassembler_ReferenceType_In_ARM64_ADR 0x100000005 138 | 139 | /* The output reference is to as symbol stub. */ 140 | #define LLVMDisassembler_ReferenceType_Out_SymbolStub 1 141 | /* The output reference is to a symbol address in a literal pool. */ 142 | #define LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr 2 143 | /* The output reference is to a cstring address in a literal pool. */ 144 | #define LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr 3 145 | 146 | /* The output reference is to a Objective-C CoreFoundation string. */ 147 | #define LLVMDisassembler_ReferenceType_Out_Objc_CFString_Ref 4 148 | /* The output reference is to a Objective-C message. */ 149 | #define LLVMDisassembler_ReferenceType_Out_Objc_Message 5 150 | /* The output reference is to a Objective-C message ref. */ 151 | #define LLVMDisassembler_ReferenceType_Out_Objc_Message_Ref 6 152 | /* The output reference is to a Objective-C selector ref. */ 153 | #define LLVMDisassembler_ReferenceType_Out_Objc_Selector_Ref 7 154 | /* The output reference is to a Objective-C class ref. */ 155 | #define LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref 8 156 | 157 | /* The output reference is to a C++ symbol name. */ 158 | #define LLVMDisassembler_ReferenceType_DeMangled_Name 9 159 | 160 | #endif 161 | -------------------------------------------------------------------------------- /third-party/include/llvm-c/ExecutionEngine.h: -------------------------------------------------------------------------------- 1 | /*===-- llvm-c/ExecutionEngine.h - ExecutionEngine Lib C Iface --*- C++ -*-===*\ 2 | |* *| 3 | |* Part of the LLVM Project, under the Apache License v2.0 with LLVM *| 4 | |* Exceptions. *| 5 | |* See https://llvm.org/LICENSE.txt for license information. *| 6 | |* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception *| 7 | |* *| 8 | |*===----------------------------------------------------------------------===*| 9 | |* *| 10 | |* This header declares the C interface to libLLVMExecutionEngine.o, which *| 11 | |* implements various analyses of the LLVM IR. *| 12 | |* *| 13 | |* Many exotic languages can interoperate with C code but have a harder time *| 14 | |* with C++ due to name mangling. So in addition to C, this interface enables *| 15 | |* tools written in such languages. *| 16 | |* *| 17 | \*===----------------------------------------------------------------------===*/ 18 | 19 | #ifndef LLVM_C_EXECUTIONENGINE_H 20 | #define LLVM_C_EXECUTIONENGINE_H 21 | 22 | #include "llvm-c/ExternC.h" 23 | #include "llvm-c/Target.h" 24 | #include "llvm-c/TargetMachine.h" 25 | #include "llvm-c/Types.h" 26 | 27 | LLVM_C_EXTERN_C_BEGIN 28 | 29 | /** 30 | * @defgroup LLVMCExecutionEngine Execution Engine 31 | * @ingroup LLVMC 32 | * 33 | * @{ 34 | */ 35 | 36 | void LLVMLinkInMCJIT(void); 37 | void LLVMLinkInInterpreter(void); 38 | 39 | typedef struct LLVMOpaqueGenericValue *LLVMGenericValueRef; 40 | typedef struct LLVMOpaqueExecutionEngine *LLVMExecutionEngineRef; 41 | typedef struct LLVMOpaqueMCJITMemoryManager *LLVMMCJITMemoryManagerRef; 42 | 43 | struct LLVMMCJITCompilerOptions { 44 | unsigned OptLevel; 45 | LLVMCodeModel CodeModel; 46 | LLVMBool NoFramePointerElim; 47 | LLVMBool EnableFastISel; 48 | LLVMMCJITMemoryManagerRef MCJMM; 49 | }; 50 | 51 | /*===-- Operations on generic values --------------------------------------===*/ 52 | 53 | LLVMGenericValueRef LLVMCreateGenericValueOfInt(LLVMTypeRef Ty, 54 | unsigned long long N, 55 | LLVMBool IsSigned); 56 | 57 | LLVMGenericValueRef LLVMCreateGenericValueOfPointer(void *P); 58 | 59 | LLVMGenericValueRef LLVMCreateGenericValueOfFloat(LLVMTypeRef Ty, double N); 60 | 61 | unsigned LLVMGenericValueIntWidth(LLVMGenericValueRef GenValRef); 62 | 63 | unsigned long long LLVMGenericValueToInt(LLVMGenericValueRef GenVal, 64 | LLVMBool IsSigned); 65 | 66 | void *LLVMGenericValueToPointer(LLVMGenericValueRef GenVal); 67 | 68 | double LLVMGenericValueToFloat(LLVMTypeRef TyRef, LLVMGenericValueRef GenVal); 69 | 70 | void LLVMDisposeGenericValue(LLVMGenericValueRef GenVal); 71 | 72 | /*===-- Operations on execution engines -----------------------------------===*/ 73 | 74 | LLVMBool LLVMCreateExecutionEngineForModule(LLVMExecutionEngineRef *OutEE, 75 | LLVMModuleRef M, 76 | char **OutError); 77 | 78 | LLVMBool LLVMCreateInterpreterForModule(LLVMExecutionEngineRef *OutInterp, 79 | LLVMModuleRef M, 80 | char **OutError); 81 | 82 | LLVMBool LLVMCreateJITCompilerForModule(LLVMExecutionEngineRef *OutJIT, 83 | LLVMModuleRef M, 84 | unsigned OptLevel, 85 | char **OutError); 86 | 87 | void LLVMInitializeMCJITCompilerOptions( 88 | struct LLVMMCJITCompilerOptions *Options, size_t SizeOfOptions); 89 | 90 | /** 91 | * Create an MCJIT execution engine for a module, with the given options. It is 92 | * the responsibility of the caller to ensure that all fields in Options up to 93 | * the given SizeOfOptions are initialized. It is correct to pass a smaller 94 | * value of SizeOfOptions that omits some fields. The canonical way of using 95 | * this is: 96 | * 97 | * LLVMMCJITCompilerOptions options; 98 | * LLVMInitializeMCJITCompilerOptions(&options, sizeof(options)); 99 | * ... fill in those options you care about 100 | * LLVMCreateMCJITCompilerForModule(&jit, mod, &options, sizeof(options), 101 | * &error); 102 | * 103 | * Note that this is also correct, though possibly suboptimal: 104 | * 105 | * LLVMCreateMCJITCompilerForModule(&jit, mod, 0, 0, &error); 106 | */ 107 | LLVMBool LLVMCreateMCJITCompilerForModule( 108 | LLVMExecutionEngineRef *OutJIT, LLVMModuleRef M, 109 | struct LLVMMCJITCompilerOptions *Options, size_t SizeOfOptions, 110 | char **OutError); 111 | 112 | void LLVMDisposeExecutionEngine(LLVMExecutionEngineRef EE); 113 | 114 | void LLVMRunStaticConstructors(LLVMExecutionEngineRef EE); 115 | 116 | void LLVMRunStaticDestructors(LLVMExecutionEngineRef EE); 117 | 118 | int LLVMRunFunctionAsMain(LLVMExecutionEngineRef EE, LLVMValueRef F, 119 | unsigned ArgC, const char * const *ArgV, 120 | const char * const *EnvP); 121 | 122 | LLVMGenericValueRef LLVMRunFunction(LLVMExecutionEngineRef EE, LLVMValueRef F, 123 | unsigned NumArgs, 124 | LLVMGenericValueRef *Args); 125 | 126 | void LLVMFreeMachineCodeForFunction(LLVMExecutionEngineRef EE, LLVMValueRef F); 127 | 128 | void LLVMAddModule(LLVMExecutionEngineRef EE, LLVMModuleRef M); 129 | 130 | LLVMBool LLVMRemoveModule(LLVMExecutionEngineRef EE, LLVMModuleRef M, 131 | LLVMModuleRef *OutMod, char **OutError); 132 | 133 | LLVMBool LLVMFindFunction(LLVMExecutionEngineRef EE, const char *Name, 134 | LLVMValueRef *OutFn); 135 | 136 | void *LLVMRecompileAndRelinkFunction(LLVMExecutionEngineRef EE, 137 | LLVMValueRef Fn); 138 | 139 | LLVMTargetDataRef LLVMGetExecutionEngineTargetData(LLVMExecutionEngineRef EE); 140 | LLVMTargetMachineRef 141 | LLVMGetExecutionEngineTargetMachine(LLVMExecutionEngineRef EE); 142 | 143 | void LLVMAddGlobalMapping(LLVMExecutionEngineRef EE, LLVMValueRef Global, 144 | void* Addr); 145 | 146 | void *LLVMGetPointerToGlobal(LLVMExecutionEngineRef EE, LLVMValueRef Global); 147 | 148 | uint64_t LLVMGetGlobalValueAddress(LLVMExecutionEngineRef EE, const char *Name); 149 | 150 | uint64_t LLVMGetFunctionAddress(LLVMExecutionEngineRef EE, const char *Name); 151 | 152 | /// Returns true on error, false on success. If true is returned then the error 153 | /// message is copied to OutStr and cleared in the ExecutionEngine instance. 154 | LLVMBool LLVMExecutionEngineGetErrMsg(LLVMExecutionEngineRef EE, 155 | char **OutError); 156 | 157 | /*===-- Operations on memory managers -------------------------------------===*/ 158 | 159 | typedef uint8_t *(*LLVMMemoryManagerAllocateCodeSectionCallback)( 160 | void *Opaque, uintptr_t Size, unsigned Alignment, unsigned SectionID, 161 | const char *SectionName); 162 | typedef uint8_t *(*LLVMMemoryManagerAllocateDataSectionCallback)( 163 | void *Opaque, uintptr_t Size, unsigned Alignment, unsigned SectionID, 164 | const char *SectionName, LLVMBool IsReadOnly); 165 | typedef LLVMBool (*LLVMMemoryManagerFinalizeMemoryCallback)( 166 | void *Opaque, char **ErrMsg); 167 | typedef void (*LLVMMemoryManagerDestroyCallback)(void *Opaque); 168 | 169 | /** 170 | * Create a simple custom MCJIT memory manager. This memory manager can 171 | * intercept allocations in a module-oblivious way. This will return NULL 172 | * if any of the passed functions are NULL. 173 | * 174 | * @param Opaque An opaque client object to pass back to the callbacks. 175 | * @param AllocateCodeSection Allocate a block of memory for executable code. 176 | * @param AllocateDataSection Allocate a block of memory for data. 177 | * @param FinalizeMemory Set page permissions and flush cache. Return 0 on 178 | * success, 1 on error. 179 | */ 180 | LLVMMCJITMemoryManagerRef LLVMCreateSimpleMCJITMemoryManager( 181 | void *Opaque, 182 | LLVMMemoryManagerAllocateCodeSectionCallback AllocateCodeSection, 183 | LLVMMemoryManagerAllocateDataSectionCallback AllocateDataSection, 184 | LLVMMemoryManagerFinalizeMemoryCallback FinalizeMemory, 185 | LLVMMemoryManagerDestroyCallback Destroy); 186 | 187 | void LLVMDisposeMCJITMemoryManager(LLVMMCJITMemoryManagerRef MM); 188 | 189 | /*===-- JIT Event Listener functions -------------------------------------===*/ 190 | 191 | LLVMJITEventListenerRef LLVMCreateGDBRegistrationListener(void); 192 | LLVMJITEventListenerRef LLVMCreateIntelJITEventListener(void); 193 | LLVMJITEventListenerRef LLVMCreateOProfileJITEventListener(void); 194 | LLVMJITEventListenerRef LLVMCreatePerfJITEventListener(void); 195 | 196 | /** 197 | * @} 198 | */ 199 | 200 | LLVM_C_EXTERN_C_END 201 | 202 | #endif 203 | -------------------------------------------------------------------------------- /third-party/include/llvm-c/Object.h: -------------------------------------------------------------------------------- 1 | /*===-- llvm-c/Object.h - Object Lib C Iface --------------------*- C++ -*-===*/ 2 | /* */ 3 | /* Part of the LLVM Project, under the Apache License v2.0 with LLVM */ 4 | /* Exceptions. */ 5 | /* See https://llvm.org/LICENSE.txt for license information. */ 6 | /* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception */ 7 | /* */ 8 | /*===----------------------------------------------------------------------===*/ 9 | /* */ 10 | /* This header declares the C interface to libLLVMObject.a, which */ 11 | /* implements object file reading and writing. */ 12 | /* */ 13 | /* Many exotic languages can interoperate with C code but have a harder time */ 14 | /* with C++ due to name mangling. So in addition to C, this interface enables */ 15 | /* tools written in such languages. */ 16 | /* */ 17 | /*===----------------------------------------------------------------------===*/ 18 | 19 | #ifndef LLVM_C_OBJECT_H 20 | #define LLVM_C_OBJECT_H 21 | 22 | #include "llvm-c/ExternC.h" 23 | #include "llvm-c/Types.h" 24 | #include "llvm/Config/llvm-config.h" 25 | 26 | LLVM_C_EXTERN_C_BEGIN 27 | 28 | /** 29 | * @defgroup LLVMCObject Object file reading and writing 30 | * @ingroup LLVMC 31 | * 32 | * @{ 33 | */ 34 | 35 | // Opaque type wrappers 36 | typedef struct LLVMOpaqueSectionIterator *LLVMSectionIteratorRef; 37 | typedef struct LLVMOpaqueSymbolIterator *LLVMSymbolIteratorRef; 38 | typedef struct LLVMOpaqueRelocationIterator *LLVMRelocationIteratorRef; 39 | 40 | typedef enum { 41 | LLVMBinaryTypeArchive, /**< Archive file. */ 42 | LLVMBinaryTypeMachOUniversalBinary, /**< Mach-O Universal Binary file. */ 43 | LLVMBinaryTypeCOFFImportFile, /**< COFF Import file. */ 44 | LLVMBinaryTypeIR, /**< LLVM IR. */ 45 | LLVMBinaryTypeWinRes, /**< Windows resource (.res) file. */ 46 | LLVMBinaryTypeCOFF, /**< COFF Object file. */ 47 | LLVMBinaryTypeELF32L, /**< ELF 32-bit, little endian. */ 48 | LLVMBinaryTypeELF32B, /**< ELF 32-bit, big endian. */ 49 | LLVMBinaryTypeELF64L, /**< ELF 64-bit, little endian. */ 50 | LLVMBinaryTypeELF64B, /**< ELF 64-bit, big endian. */ 51 | LLVMBinaryTypeMachO32L, /**< MachO 32-bit, little endian. */ 52 | LLVMBinaryTypeMachO32B, /**< MachO 32-bit, big endian. */ 53 | LLVMBinaryTypeMachO64L, /**< MachO 64-bit, little endian. */ 54 | LLVMBinaryTypeMachO64B, /**< MachO 64-bit, big endian. */ 55 | LLVMBinaryTypeWasm, /**< Web Assembly. */ 56 | } LLVMBinaryType; 57 | 58 | /** 59 | * Create a binary file from the given memory buffer. 60 | * 61 | * The exact type of the binary file will be inferred automatically, and the 62 | * appropriate implementation selected. The context may be NULL except if 63 | * the resulting file is an LLVM IR file. 64 | * 65 | * The memory buffer is not consumed by this function. It is the responsibilty 66 | * of the caller to free it with \c LLVMDisposeMemoryBuffer. 67 | * 68 | * If NULL is returned, the \p ErrorMessage parameter is populated with the 69 | * error's description. It is then the caller's responsibility to free this 70 | * message by calling \c LLVMDisposeMessage. 71 | * 72 | * @see llvm::object::createBinary 73 | */ 74 | LLVMBinaryRef LLVMCreateBinary(LLVMMemoryBufferRef MemBuf, 75 | LLVMContextRef Context, 76 | char **ErrorMessage); 77 | 78 | /** 79 | * Dispose of a binary file. 80 | * 81 | * The binary file does not own its backing buffer. It is the responsibilty 82 | * of the caller to free it with \c LLVMDisposeMemoryBuffer. 83 | */ 84 | void LLVMDisposeBinary(LLVMBinaryRef BR); 85 | 86 | /** 87 | * Retrieves a copy of the memory buffer associated with this object file. 88 | * 89 | * The returned buffer is merely a shallow copy and does not own the actual 90 | * backing buffer of the binary. Nevertheless, it is the responsibility of the 91 | * caller to free it with \c LLVMDisposeMemoryBuffer. 92 | * 93 | * @see llvm::object::getMemoryBufferRef 94 | */ 95 | LLVMMemoryBufferRef LLVMBinaryCopyMemoryBuffer(LLVMBinaryRef BR); 96 | 97 | /** 98 | * Retrieve the specific type of a binary. 99 | * 100 | * @see llvm::object::Binary::getType 101 | */ 102 | LLVMBinaryType LLVMBinaryGetType(LLVMBinaryRef BR); 103 | 104 | /* 105 | * For a Mach-O universal binary file, retrieves the object file corresponding 106 | * to the given architecture if it is present as a slice. 107 | * 108 | * If NULL is returned, the \p ErrorMessage parameter is populated with the 109 | * error's description. It is then the caller's responsibility to free this 110 | * message by calling \c LLVMDisposeMessage. 111 | * 112 | * It is the responsiblity of the caller to free the returned object file by 113 | * calling \c LLVMDisposeBinary. 114 | */ 115 | LLVMBinaryRef LLVMMachOUniversalBinaryCopyObjectForArch(LLVMBinaryRef BR, 116 | const char *Arch, 117 | size_t ArchLen, 118 | char **ErrorMessage); 119 | 120 | /** 121 | * Retrieve a copy of the section iterator for this object file. 122 | * 123 | * If there are no sections, the result is NULL. 124 | * 125 | * The returned iterator is merely a shallow copy. Nevertheless, it is 126 | * the responsibility of the caller to free it with 127 | * \c LLVMDisposeSectionIterator. 128 | * 129 | * @see llvm::object::sections() 130 | */ 131 | LLVMSectionIteratorRef LLVMObjectFileCopySectionIterator(LLVMBinaryRef BR); 132 | 133 | /** 134 | * Returns whether the given section iterator is at the end. 135 | * 136 | * @see llvm::object::section_end 137 | */ 138 | LLVMBool LLVMObjectFileIsSectionIteratorAtEnd(LLVMBinaryRef BR, 139 | LLVMSectionIteratorRef SI); 140 | 141 | /** 142 | * Retrieve a copy of the symbol iterator for this object file. 143 | * 144 | * If there are no symbols, the result is NULL. 145 | * 146 | * The returned iterator is merely a shallow copy. Nevertheless, it is 147 | * the responsibility of the caller to free it with 148 | * \c LLVMDisposeSymbolIterator. 149 | * 150 | * @see llvm::object::symbols() 151 | */ 152 | LLVMSymbolIteratorRef LLVMObjectFileCopySymbolIterator(LLVMBinaryRef BR); 153 | 154 | /** 155 | * Returns whether the given symbol iterator is at the end. 156 | * 157 | * @see llvm::object::symbol_end 158 | */ 159 | LLVMBool LLVMObjectFileIsSymbolIteratorAtEnd(LLVMBinaryRef BR, 160 | LLVMSymbolIteratorRef SI); 161 | 162 | void LLVMDisposeSectionIterator(LLVMSectionIteratorRef SI); 163 | 164 | void LLVMMoveToNextSection(LLVMSectionIteratorRef SI); 165 | void LLVMMoveToContainingSection(LLVMSectionIteratorRef Sect, 166 | LLVMSymbolIteratorRef Sym); 167 | 168 | // ObjectFile Symbol iterators 169 | void LLVMDisposeSymbolIterator(LLVMSymbolIteratorRef SI); 170 | void LLVMMoveToNextSymbol(LLVMSymbolIteratorRef SI); 171 | 172 | // SectionRef accessors 173 | const char *LLVMGetSectionName(LLVMSectionIteratorRef SI); 174 | uint64_t LLVMGetSectionSize(LLVMSectionIteratorRef SI); 175 | const char *LLVMGetSectionContents(LLVMSectionIteratorRef SI); 176 | uint64_t LLVMGetSectionAddress(LLVMSectionIteratorRef SI); 177 | LLVMBool LLVMGetSectionContainsSymbol(LLVMSectionIteratorRef SI, 178 | LLVMSymbolIteratorRef Sym); 179 | 180 | // Section Relocation iterators 181 | LLVMRelocationIteratorRef LLVMGetRelocations(LLVMSectionIteratorRef Section); 182 | void LLVMDisposeRelocationIterator(LLVMRelocationIteratorRef RI); 183 | LLVMBool LLVMIsRelocationIteratorAtEnd(LLVMSectionIteratorRef Section, 184 | LLVMRelocationIteratorRef RI); 185 | void LLVMMoveToNextRelocation(LLVMRelocationIteratorRef RI); 186 | 187 | 188 | // SymbolRef accessors 189 | const char *LLVMGetSymbolName(LLVMSymbolIteratorRef SI); 190 | uint64_t LLVMGetSymbolAddress(LLVMSymbolIteratorRef SI); 191 | uint64_t LLVMGetSymbolSize(LLVMSymbolIteratorRef SI); 192 | 193 | // RelocationRef accessors 194 | uint64_t LLVMGetRelocationOffset(LLVMRelocationIteratorRef RI); 195 | LLVMSymbolIteratorRef LLVMGetRelocationSymbol(LLVMRelocationIteratorRef RI); 196 | uint64_t LLVMGetRelocationType(LLVMRelocationIteratorRef RI); 197 | // NOTE: Caller takes ownership of returned string of the two 198 | // following functions. 199 | const char *LLVMGetRelocationTypeName(LLVMRelocationIteratorRef RI); 200 | const char *LLVMGetRelocationValueString(LLVMRelocationIteratorRef RI); 201 | 202 | /** Deprecated: Use LLVMBinaryRef instead. */ 203 | typedef struct LLVMOpaqueObjectFile *LLVMObjectFileRef; 204 | 205 | /** Deprecated: Use LLVMCreateBinary instead. */ 206 | LLVMObjectFileRef LLVMCreateObjectFile(LLVMMemoryBufferRef MemBuf); 207 | 208 | /** Deprecated: Use LLVMDisposeBinary instead. */ 209 | void LLVMDisposeObjectFile(LLVMObjectFileRef ObjectFile); 210 | 211 | /** Deprecated: Use LLVMObjectFileCopySectionIterator instead. */ 212 | LLVMSectionIteratorRef LLVMGetSections(LLVMObjectFileRef ObjectFile); 213 | 214 | /** Deprecated: Use LLVMObjectFileIsSectionIteratorAtEnd instead. */ 215 | LLVMBool LLVMIsSectionIteratorAtEnd(LLVMObjectFileRef ObjectFile, 216 | LLVMSectionIteratorRef SI); 217 | 218 | /** Deprecated: Use LLVMObjectFileCopySymbolIterator instead. */ 219 | LLVMSymbolIteratorRef LLVMGetSymbols(LLVMObjectFileRef ObjectFile); 220 | 221 | /** Deprecated: Use LLVMObjectFileIsSymbolIteratorAtEnd instead. */ 222 | LLVMBool LLVMIsSymbolIteratorAtEnd(LLVMObjectFileRef ObjectFile, 223 | LLVMSymbolIteratorRef SI); 224 | /** 225 | * @} 226 | */ 227 | 228 | LLVM_C_EXTERN_C_END 229 | 230 | #endif 231 | -------------------------------------------------------------------------------- /third-party/include/llvm-c/LLJIT.h: -------------------------------------------------------------------------------- 1 | /*===----------- llvm-c/LLJIT.h - OrcV2 LLJIT C bindings --------*- C++ -*-===*\ 2 | |* *| 3 | |* Part of the LLVM Project, under the Apache License v2.0 with LLVM *| 4 | |* Exceptions. *| 5 | |* See https://llvm.org/LICENSE.txt for license information. *| 6 | |* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception *| 7 | |* *| 8 | |*===----------------------------------------------------------------------===*| 9 | |* *| 10 | |* This header declares the C interface to the LLJIT class in *| 11 | |* libLLVMOrcJIT.a, which provides a simple MCJIT-like ORC JIT. *| 12 | |* *| 13 | |* Many exotic languages can interoperate with C code but have a harder time *| 14 | |* with C++ due to name mangling. So in addition to C, this interface enables *| 15 | |* tools written in such languages. *| 16 | |* *| 17 | |* Note: This interface is experimental. It is *NOT* stable, and may be *| 18 | |* changed without warning. Only C API usage documentation is *| 19 | |* provided. See the C++ documentation for all higher level ORC API *| 20 | |* details. *| 21 | |* *| 22 | \*===----------------------------------------------------------------------===*/ 23 | 24 | #ifndef LLVM_C_LLJIT_H 25 | #define LLVM_C_LLJIT_H 26 | 27 | #include "llvm-c/Error.h" 28 | #include "llvm-c/Orc.h" 29 | #include "llvm-c/TargetMachine.h" 30 | #include "llvm-c/Types.h" 31 | 32 | LLVM_C_EXTERN_C_BEGIN 33 | 34 | /** 35 | * A function for constructing an ObjectLinkingLayer instance to be used 36 | * by an LLJIT instance. 37 | * 38 | * Clients can call LLVMOrcLLJITBuilderSetObjectLinkingLayerCreator to 39 | * set the creator function to use when constructing an LLJIT instance. 40 | * This can be used to override the default linking layer implementation 41 | * that would otherwise be chosen by LLJITBuilder. 42 | * 43 | * Object linking layers returned by this function will become owned by the 44 | * LLJIT instance. The client is not responsible for managing their lifetimes 45 | * after the function returns. 46 | */ 47 | typedef LLVMOrcObjectLayerRef ( 48 | *LLVMOrcLLJITBuilderObjectLinkingLayerCreatorFunction)( 49 | void *Ctx, LLVMOrcExecutionSessionRef ES, const char *Triple); 50 | 51 | /** 52 | * A reference to an orc::LLJITBuilder instance. 53 | */ 54 | typedef struct LLVMOrcOpaqueLLJITBuilder *LLVMOrcLLJITBuilderRef; 55 | 56 | /** 57 | * A reference to an orc::LLJIT instance. 58 | */ 59 | typedef struct LLVMOrcOpaqueLLJIT *LLVMOrcLLJITRef; 60 | 61 | /** 62 | * Create an LLVMOrcLLJITBuilder. 63 | * 64 | * The client owns the resulting LLJITBuilder and should dispose of it using 65 | * LLVMOrcDisposeLLJITBuilder once they are done with it. 66 | */ 67 | LLVMOrcLLJITBuilderRef LLVMOrcCreateLLJITBuilder(void); 68 | 69 | /** 70 | * Dispose of an LLVMOrcLLJITBuilderRef. This should only be called if ownership 71 | * has not been passed to LLVMOrcCreateLLJIT (e.g. because some error prevented 72 | * that function from being called). 73 | */ 74 | void LLVMOrcDisposeLLJITBuilder(LLVMOrcLLJITBuilderRef Builder); 75 | 76 | /** 77 | * Set the JITTargetMachineBuilder to be used when constructing the LLJIT 78 | * instance. Calling this function is optional: if it is not called then the 79 | * LLJITBuilder will use JITTargeTMachineBuilder::detectHost to construct a 80 | * JITTargetMachineBuilder. 81 | * 82 | * This function takes ownership of the JTMB argument: clients should not 83 | * dispose of the JITTargetMachineBuilder after calling this function. 84 | */ 85 | void LLVMOrcLLJITBuilderSetJITTargetMachineBuilder( 86 | LLVMOrcLLJITBuilderRef Builder, LLVMOrcJITTargetMachineBuilderRef JTMB); 87 | 88 | /** 89 | * Set an ObjectLinkingLayer creator function for this LLJIT instance. 90 | */ 91 | void LLVMOrcLLJITBuilderSetObjectLinkingLayerCreator( 92 | LLVMOrcLLJITBuilderRef Builder, 93 | LLVMOrcLLJITBuilderObjectLinkingLayerCreatorFunction F, void *Ctx); 94 | 95 | /** 96 | * Create an LLJIT instance from an LLJITBuilder. 97 | * 98 | * This operation takes ownership of the Builder argument: clients should not 99 | * dispose of the builder after calling this function (even if the function 100 | * returns an error). If a null Builder argument is provided then a 101 | * default-constructed LLJITBuilder will be used. 102 | * 103 | * On success the resulting LLJIT instance is uniquely owned by the client and 104 | * automatically manages the memory of all JIT'd code and all modules that are 105 | * transferred to it (e.g. via LLVMOrcLLJITAddLLVMIRModule). Disposing of the 106 | * LLJIT instance will free all memory managed by the JIT, including JIT'd code 107 | * and not-yet compiled modules. 108 | */ 109 | LLVMErrorRef LLVMOrcCreateLLJIT(LLVMOrcLLJITRef *Result, 110 | LLVMOrcLLJITBuilderRef Builder); 111 | 112 | /** 113 | * Dispose of an LLJIT instance. 114 | */ 115 | LLVMErrorRef LLVMOrcDisposeLLJIT(LLVMOrcLLJITRef J); 116 | 117 | /** 118 | * Get a reference to the ExecutionSession for this LLJIT instance. 119 | * 120 | * The ExecutionSession is owned by the LLJIT instance. The client is not 121 | * responsible for managing its memory. 122 | */ 123 | LLVMOrcExecutionSessionRef LLVMOrcLLJITGetExecutionSession(LLVMOrcLLJITRef J); 124 | 125 | /** 126 | * Return a reference to the Main JITDylib. 127 | * 128 | * The JITDylib is owned by the LLJIT instance. The client is not responsible 129 | * for managing its memory. 130 | */ 131 | LLVMOrcJITDylibRef LLVMOrcLLJITGetMainJITDylib(LLVMOrcLLJITRef J); 132 | 133 | /** 134 | * Return the target triple for this LLJIT instance. This string is owned by 135 | * the LLJIT instance and should not be freed by the client. 136 | */ 137 | const char *LLVMOrcLLJITGetTripleString(LLVMOrcLLJITRef J); 138 | 139 | /** 140 | * Returns the global prefix character according to the LLJIT's DataLayout. 141 | */ 142 | char LLVMOrcLLJITGetGlobalPrefix(LLVMOrcLLJITRef J); 143 | 144 | /** 145 | * Mangles the given string according to the LLJIT instance's DataLayout, then 146 | * interns the result in the SymbolStringPool and returns a reference to the 147 | * pool entry. Clients should call LLVMOrcReleaseSymbolStringPoolEntry to 148 | * decrement the ref-count on the pool entry once they are finished with this 149 | * value. 150 | */ 151 | LLVMOrcSymbolStringPoolEntryRef 152 | LLVMOrcLLJITMangleAndIntern(LLVMOrcLLJITRef J, const char *UnmangledName); 153 | 154 | /** 155 | * Add a buffer representing an object file to the given JITDylib in the given 156 | * LLJIT instance. This operation transfers ownership of the buffer to the 157 | * LLJIT instance. The buffer should not be disposed of or referenced once this 158 | * function returns. 159 | * 160 | * Resources associated with the given object will be tracked by the given 161 | * JITDylib's default resource tracker. 162 | */ 163 | LLVMErrorRef LLVMOrcLLJITAddObjectFile(LLVMOrcLLJITRef J, LLVMOrcJITDylibRef JD, 164 | LLVMMemoryBufferRef ObjBuffer); 165 | 166 | /** 167 | * Add a buffer representing an object file to the given ResourceTracker's 168 | * JITDylib in the given LLJIT instance. This operation transfers ownership of 169 | * the buffer to the LLJIT instance. The buffer should not be disposed of or 170 | * referenced once this function returns. 171 | * 172 | * Resources associated with the given object will be tracked by ResourceTracker 173 | * RT. 174 | */ 175 | LLVMErrorRef LLVMOrcLLJITAddObjectFileWithRT(LLVMOrcLLJITRef J, 176 | LLVMOrcResourceTrackerRef RT, 177 | LLVMMemoryBufferRef ObjBuffer); 178 | 179 | /** 180 | * Add an IR module to the given JITDylib in the given LLJIT instance. This 181 | * operation transfers ownership of the TSM argument to the LLJIT instance. 182 | * The TSM argument should not be disposed of or referenced once this 183 | * function returns. 184 | * 185 | * Resources associated with the given Module will be tracked by the given 186 | * JITDylib's default resource tracker. 187 | */ 188 | LLVMErrorRef LLVMOrcLLJITAddLLVMIRModule(LLVMOrcLLJITRef J, 189 | LLVMOrcJITDylibRef JD, 190 | LLVMOrcThreadSafeModuleRef TSM); 191 | 192 | /** 193 | * Add an IR module to the given ResourceTracker's JITDylib in the given LLJIT 194 | * instance. This operation transfers ownership of the TSM argument to the LLJIT 195 | * instance. The TSM argument should not be disposed of or referenced once this 196 | * function returns. 197 | * 198 | * Resources associated with the given Module will be tracked by ResourceTracker 199 | * RT. 200 | */ 201 | LLVMErrorRef LLVMOrcLLJITAddLLVMIRModuleWithRT(LLVMOrcLLJITRef J, 202 | LLVMOrcResourceTrackerRef JD, 203 | LLVMOrcThreadSafeModuleRef TSM); 204 | 205 | /** 206 | * Look up the given symbol in the main JITDylib of the given LLJIT instance. 207 | * 208 | * This operation does not take ownership of the Name argument. 209 | */ 210 | LLVMErrorRef LLVMOrcLLJITLookup(LLVMOrcLLJITRef J, 211 | LLVMOrcExecutorAddress *Result, 212 | const char *Name); 213 | 214 | /** 215 | * Returns a non-owning reference to the LLJIT instance's object linking layer. 216 | */ 217 | LLVMOrcObjectLayerRef LLVMOrcLLJITGetObjLinkingLayer(LLVMOrcLLJITRef J); 218 | 219 | /** 220 | * Returns a non-owning reference to the LLJIT instance's object linking layer. 221 | */ 222 | LLVMOrcObjectTransformLayerRef 223 | LLVMOrcLLJITGetObjTransformLayer(LLVMOrcLLJITRef J); 224 | 225 | /** 226 | * Returns a non-owning reference to the LLJIT instance's IR transform layer. 227 | */ 228 | LLVMOrcIRTransformLayerRef LLVMOrcLLJITGetIRTransformLayer(LLVMOrcLLJITRef J); 229 | 230 | /** 231 | * Get the LLJIT instance's default data layout string. 232 | * 233 | * This string is owned by the LLJIT instance and does not need to be freed 234 | * by the caller. 235 | */ 236 | const char *LLVMOrcLLJITGetDataLayoutStr(LLVMOrcLLJITRef J); 237 | 238 | LLVM_C_EXTERN_C_END 239 | 240 | #endif /* LLVM_C_LLJIT_H */ 241 | -------------------------------------------------------------------------------- /source/base/ds.h: -------------------------------------------------------------------------------- 1 | /* date = February 16th 2022 0:27 pm */ 2 | 3 | #ifndef DS_H 4 | #define DS_H 5 | 6 | #include "defines.h" 7 | #include 8 | 9 | #define DoubleCapacity(x) ((x) <= 0 ? 8 : x * 2) 10 | 11 | #define darray(type) type##_array 12 | 13 | #define darray_add(type, array, data) type##_array##_add(array, data) 14 | #define darray_add_all(type, array, data, count) type##_array##_add_all(array, data, count) 15 | #define darray_add_at(type, array, data, idx) type##_array##_add_at(array, data, idx) 16 | #define darray_reserve(type, array, count) type##_array##_reserve(array, count) 17 | #define darray_remove(type, array, idx) type##_array##_remove(array, idx) 18 | #define darray_free(type, array) type##_array##_free(array) 19 | 20 | #define DArray_Prototype(Data) \ 21 | typedef struct Data##_array {\ 22 | u32 cap;\ 23 | u32 len;\ 24 | Data* elems;\ 25 | } Data##_array;\ 26 | void Data##_array##_add(Data##_array* array, Data data);\ 27 | void Data##_array##_add_all(Data##_array* array, Data* data, u32 count);\ 28 | void Data##_array##_add_at(Data##_array* array, Data data, u32 idx);\ 29 | void Data##_array##_reserve(Data##_array* array, u32 count);\ 30 | Data Data##_array##_remove(Data##_array* array, int idx);\ 31 | void Data##_array##_free(Data##_array* array); 32 | 33 | #define DArray_Impl(Data) \ 34 | void Data##_array##_add(Data##_array* array, Data data) {\ 35 | if (array->len + 1 > array->cap) {\ 36 | void* prev = array->elems;\ 37 | u32 new_cap = DoubleCapacity(array->cap);\ 38 | array->elems = calloc(new_cap, sizeof(Data));\ 39 | memmove(array->elems, prev, array->len * sizeof(Data));\ 40 | array->cap = new_cap;\ 41 | free(prev);\ 42 | }\ 43 | array->elems[array->len++] = data;\ 44 | }\ 45 | void Data##_array##_add_all(Data##_array* array, Data* data, u32 count) {\ 46 | if (array->len + count > array->cap) {\ 47 | void* prev = array->elems;\ 48 | u32 new_cap = DoubleCapacity(array->cap);\ 49 | array->elems = calloc(new_cap, sizeof(Data));\ 50 | memmove(array->elems, prev, array->len * sizeof(Data));\ 51 | array->cap = new_cap;\ 52 | free(prev);\ 53 | }\ 54 | memmove(&array->elems[array->len], data, count * sizeof(Data));\ 55 | array->len += count;\ 56 | }\ 57 | void Data##_array##_add_at(Data##_array* array, Data data, u32 idx) {\ 58 | if (array->len + 1 > array->cap) {\ 59 | void* prev = array->elems;\ 60 | u32 new_cap = DoubleCapacity(array->cap);\ 61 | array->elems = calloc(new_cap, sizeof(Data));\ 62 | memmove(array->elems, prev, array->len * sizeof(Data));\ 63 | array->cap = new_cap;\ 64 | free(prev);\ 65 | }\ 66 | memmove(array->elems + idx + 1, array->elems + idx, sizeof(Data) * (array->len - idx));\ 67 | array->elems[idx] = data;\ 68 | array->len++;\ 69 | }\ 70 | void Data##_array##_reserve(Data##_array* array, u32 count) {\ 71 | void* prev = array->elems;\ 72 | u32 new_cap = count;\ 73 | array->elems = calloc(new_cap, sizeof(Data));\ 74 | memmove(array->elems, prev, array->len * sizeof(Data));\ 75 | array->cap = new_cap;\ 76 | if (prev) free(prev);\ 77 | }\ 78 | Data Data##_array##_remove(Data##_array* array, int idx) {\ 79 | if (idx >= array->len || idx < 0) return (Data){0};\ 80 | Data value = array->elems[idx];\ 81 | if (idx == array->len - 1) {\ 82 | array->len--;\ 83 | return value;\ 84 | }\ 85 | Data* from = array->elems + idx + 1;\ 86 | Data* to = array->elems + idx;\ 87 | memmove(to, from, sizeof(Data) * (array->len - idx - 1));\ 88 | array->len--;\ 89 | return value;\ 90 | }\ 91 | void Data##_array##_free(Data##_array* array) {\ 92 | array->cap = 0;\ 93 | array->len = 0;\ 94 | free(array->elems);\ 95 | } 96 | 97 | #define dstack(type) type##_stack 98 | 99 | #define dstack_push(type, stack, data) type##_stack##_push(stack, data) 100 | #define dstack_pop(type, stack) type##_stack##_pop(stack) 101 | #define dstack_peek(type, stack) type##_stack##_peek(stack) 102 | #define dstack_free(type, stack) type##_stack##_free(stack) 103 | 104 | #define Stack_Prototype(Data) \ 105 | typedef struct Data##_stack {\ 106 | u32 cap;\ 107 | u32 len;\ 108 | Data* elems;\ 109 | } Data##_stack;\ 110 | void Data##_stack##_push(Data##_stack* stack, Data data);\ 111 | Data Data##_stack##_pop(Data##_stack* stack);\ 112 | Data Data##_stack##_peek(Data##_stack* stack);\ 113 | void Data##_stack##_free(Data##_stack* stack); 114 | 115 | #define Stack_Impl(Data)\ 116 | void Data##_stack##_push(Data##_stack* stack, Data data) {\ 117 | if (stack->len + 1 > stack->cap) {\ 118 | void* prev = stack->elems;\ 119 | u32 new_cap = DoubleCapacity(stack->cap);\ 120 | stack->elems = calloc(new_cap, sizeof(Data));\ 121 | memmove(stack->elems, prev, stack->len * sizeof(Data));\ 122 | free(prev);\ 123 | }\ 124 | stack->elems[stack->len++] = data;\ 125 | }\ 126 | Data Data##_stack##_pop(Data##_stack* stack) {\ 127 | if (stack->len == 0) return (Data){0};\ 128 | return stack->elems[--stack->len];\ 129 | }\ 130 | Data Data##_stack##_peek(Data##_stack* stack) {\ 131 | if (stack->len == 0) return (Data){0};\ 132 | return stack->elems[stack->len - 1];\ 133 | }\ 134 | void Data##_stack##_free(Data##_stack* stack) {\ 135 | stack->cap = 0;\ 136 | stack->len = 0;\ 137 | free(stack->elems);\ 138 | } 139 | 140 | #define HashTable_MaxLoad 0.75 141 | 142 | #define hash_table_key(key, value) key##_##value##_hash_table_key 143 | #define hash_table_value(key, value) key##_##value##_hash_table_value 144 | #define hash_table_entry(key, value) key##_##value##_hash_table_entry 145 | #define hash_table(key, value) key##_##value##_hash_table 146 | 147 | #define hash_table_init(key_t, value_t, table) key_t##_##value_t##_hash_table_init(table) 148 | #define hash_table_set(key_t, value_t, table, key, val) key_t##_##value_t##_hash_table_set(table, key, val) 149 | #define hash_table_get(key_t, value_t, table, key, val) key_t##_##value_t##_hash_table_get(table, key, val) 150 | #define hash_table_del(key_t, value_t, table, key, val) key_t##_##value_t##_hash_table_del(table, key) 151 | #define hash_table_add_all(key_t, value_t, to, from) key_t##_##value_t##_hash_table_del(to, from) 152 | #define hash_table_free(key_t, value_t, table) key_t##_##value_t##_hash_table_free(table) 153 | 154 | #define HashTable_Prototype(Key, Value)\ 155 | typedef Key Key##_##Value##_hash_table_key;\ 156 | typedef Value Key##_##Value##_hash_table_value;\ 157 | typedef struct Key##_##Value##_hash_table_entry {\ 158 | Key##_##Value##_hash_table_key key;\ 159 | Key##_##Value##_hash_table_value value;\ 160 | } Key##_##Value##_hash_table_entry;\ 161 | typedef struct Key##_##Value##_hash_table {\ 162 | u32 cap;\ 163 | u32 len;\ 164 | Key##_##Value##_hash_table_entry* elems;\ 165 | } Key##_##Value##_hash_table;\ 166 | void Key##_##Value##_hash_table_init(Key##_##Value##_hash_table* table);\ 167 | void Key##_##Value##_hash_table_free(Key##_##Value##_hash_table* table);\ 168 | b8 Key##_##Value##_hash_table_get(Key##_##Value##_hash_table* table, Key##_##Value##_hash_table_key key, Key##_##Value##_hash_table_value* val);\ 169 | b8 Key##_##Value##_hash_table_set(Key##_##Value##_hash_table* table, Key##_##Value##_hash_table_key key, Key##_##Value##_hash_table_value val);\ 170 | b8 Key##_##Value##_hash_table_del(Key##_##Value##_hash_table* table, Key##_##Value##_hash_table_key key);\ 171 | void Key##_##Value##_hash_table_add_all(Key##_##Value##_hash_table* to, Key##_##Value##_hash_table* from); 172 | 173 | #define HashTable_Impl(Key, Value, KeyIsNull, KeyIsEqual, HashKey, Tombstone, ValIsNull, ValIsTombstone)\ 174 | static const Key##_##Value##_hash_table_value Key##_##Value##_hash_table_tombstone = Tombstone;\ 175 | void Key##_##Value##_hash_table_init(Key##_##Value##_hash_table* table) {\ 176 | table->cap = 0;\ 177 | table->len = 0;\ 178 | table->elems = nullptr;\ 179 | }\ 180 | void Key##_##Value##_hash_table_free(Key##_##Value##_hash_table* table) {\ 181 | free(table->elems);\ 182 | table->cap = 0;\ 183 | table->len = 0;\ 184 | table->elems = nullptr;\ 185 | }\ 186 | static Key##_##Value##_hash_table_entry* Key##_##Value##_hash_table_find_entry(Key##_##Value##_hash_table_entry* entries, u32 cap, Key##_##Value##_hash_table_key key) {\ 187 | u32 index = HashKey(key) % cap;\ 188 | Key##_##Value##_hash_table_entry* tombstone = nullptr;\ 189 | while (true) {\ 190 | Key##_##Value##_hash_table_entry* entry = &entries[index];\ 191 | if (KeyIsNull(entry->key)) {\ 192 | if (ValIsNull(entry->value))\ 193 | return tombstone != nullptr ? tombstone : entry;\ 194 | else {\ 195 | if (tombstone == nullptr) tombstone = entry;\ 196 | }\ 197 | } else if (KeyIsEqual(entry->key, key))\ 198 | return entry;\ 199 | index = (index + 1) % cap;\ 200 | }\ 201 | }\ 202 | static void Key##_##Value##_hash_table_adjust_cap(Key##_##Value##_hash_table* table, u32 cap) {\ 203 | Key##_##Value##_hash_table_entry* entries = calloc(cap, sizeof(Key##_##Value##_hash_table_entry));\ 204 | table->len = 0;\ 205 | for (u32 i = 0; i < table->cap; i++) {\ 206 | Key##_##Value##_hash_table_entry* curr = &table->elems[i];\ 207 | if (KeyIsNull(curr->key)) continue;\ 208 | Key##_##Value##_hash_table_entry* dest = Key##_##Value##_hash_table_find_entry(entries, cap, curr->key);\ 209 | dest->key = curr->key;\ 210 | dest->value = curr->value;\ 211 | table->len++;\ 212 | }\ 213 | free(table->elems);\ 214 | table->cap = cap;\ 215 | table->elems = entries;\ 216 | }\ 217 | b8 Key##_##Value##_hash_table_set(Key##_##Value##_hash_table* table, Key##_##Value##_hash_table_key key, Key##_##Value##_hash_table_value val) {\ 218 | if (table->len + 1 > table->cap * HashTable_MaxLoad) {\ 219 | u32 cap = DoubleCapacity(table->cap);\ 220 | Key##_##Value##_hash_table_adjust_cap(table, cap);\ 221 | }\ 222 | Key##_##Value##_hash_table_entry* entry = Key##_##Value##_hash_table_find_entry(table->elems, table->cap, key);\ 223 | b8 is_new_key = KeyIsNull(entry->key);\ 224 | if (is_new_key && ValIsNull(entry->value)) table->len++;\ 225 | entry->key = key;\ 226 | entry->value = val;\ 227 | return is_new_key;\ 228 | }\ 229 | void Key##_##Value##_hash_table_add_all(Key##_##Value##_hash_table* to, Key##_##Value##_hash_table* from) {\ 230 | for (u32 i = 0; i < from->cap; i++) {\ 231 | Key##_##Value##_hash_table_entry* e = &from->elems[i];\ 232 | if (KeyIsNull(e->key)) continue;\ 233 | Key##_##Value##_hash_table_set(to, e->key, e->value);\ 234 | }\ 235 | }\ 236 | b8 Key##_##Value##_hash_table_get(Key##_##Value##_hash_table* table, Key##_##Value##_hash_table_key key, Key##_##Value##_hash_table_value* val) {\ 237 | if (table->len == 0) return false;\ 238 | Key##_##Value##_hash_table_entry* entry = Key##_##Value##_hash_table_find_entry(table->elems, table->cap, key);\ 239 | if (KeyIsNull(entry->key)) return false;\ 240 | if (val != nullptr) *val = entry->value;\ 241 | return true;\ 242 | }\ 243 | b8 Key##_##Value##_hash_table_del(Key##_##Value##_hash_table* table, Key##_##Value##_hash_table_key key) {\ 244 | if (table->len == 0) return false;\ 245 | Key##_##Value##_hash_table_entry* entry = Key##_##Value##_hash_table_find_entry(table->elems, table->cap, key);\ 246 | if (KeyIsNull(entry->key)) return false;\ 247 | entry->key = (Key##_##Value##_hash_table_key) {0};\ 248 | entry->value = Key##_##Value##_hash_table_tombstone;\ 249 | return true;\ 250 | }\ 251 | 252 | #endif //DS_H 253 | --------------------------------------------------------------------------------