1 2 3[](https://securityscorecards.dev/viewer/?uri=github.com/KhronosGroup/glslang) 4 5# News 6 71. `OGLCompiler` and `HLSL` stub libraries have been fully removed from the build. 8 92. `OVERRIDE_MSVCCRT` has been removed in favor of `CMAKE_MSVC_RUNTIME_LIBRARY` 10 11Users are encouraged to utilize the standard approach via [CMAKE_MSVC_RUNTIME_LIBRARY](https://cmake.org/cmake/help/latest/variable/CMAKE_MSVC_RUNTIME_LIBRARY.html). 12 13# Glslang Components and Status 14 15There are several components: 16 17### Reference Validator and GLSL/ESSL -> AST Front End 18 19An OpenGL GLSL and OpenGL|ES GLSL (ESSL) front-end for reference validation and translation of GLSL/ESSL into an internal abstract syntax tree (AST). 20 21**Status**: Virtually complete, with results carrying similar weight as the specifications. 22 23### HLSL -> AST Front End 24 25An HLSL front-end for translation of an approximation of HLSL to glslang's AST form. 26 27**Status**: Partially complete. Semantics are not reference quality and input is not validated. 28This is in contrast to the [DXC project](https://github.com/Microsoft/DirectXShaderCompiler), which receives a much larger investment and attempts to have definitive/reference-level semantics. 29 30See [issue 362](https://github.com/KhronosGroup/glslang/issues/362) and [issue 701](https://github.com/KhronosGroup/glslang/issues/701) for current status. 31 32### AST -> SPIR-V Back End 33 34Translates glslang's AST to the Khronos-specified SPIR-V intermediate language. 35 36**Status**: Virtually complete. 37 38### Reflector 39 40An API for getting reflection information from the AST, reflection types/variables/etc. from the HLL source (not the SPIR-V). 41 42**Status**: There is a large amount of functionality present, but no specification/goal to measure completeness against. It is accurate for the input HLL and AST, but only approximate for what would later be emitted for SPIR-V. 43 44### Standalone Wrapper 45 46`glslang` is command-line tool for accessing the functionality above. 47 48Status: Complete. 49 50Tasks waiting to be done are documented as GitHub issues. 51 52## Other References 53 54Also see the Khronos landing page for glslang as a reference front end: 55 56https://www.khronos.org/opengles/sdk/tools/Reference-Compiler/ 57 58The above page, while not kept up to date, includes additional information regarding glslang as a reference validator. 59 60# How to Use Glslang 61 62## Execution of Standalone Wrapper 63 64To use the standalone binary form, execute `glslang`, and it will print 65a usage statement. Basic operation is to give it a file containing a shader, 66and it will print out warnings/errors and optionally an AST. 67 68The applied stage-specific rules are based on the file extension: 69* `.vert` for a vertex shader 70* `.tesc` for a tessellation control shader 71* `.tese` for a tessellation evaluation shader 72* `.geom` for a geometry shader 73* `.frag` for a fragment shader 74* `.comp` for a compute shader 75 76For ray tracing pipeline shaders: 77* `.rgen` for a ray generation shader 78* `.rint` for a ray intersection shader 79* `.rahit` for a ray any-hit shader 80* `.rchit` for a ray closest-hit shader 81* `.rmiss` for a ray miss shader 82* `.rcall` for a callable shader 83 84There is also a non-shader extension: 85* `.conf` for a configuration file of limits, see usage statement for example 86 87## Building (CMake) 88 89Instead of building manually, you can also download the binaries for your 90platform directly from the [main-tot release][main-tot-release] on GitHub. 91Those binaries are automatically uploaded by the buildbots after successful 92testing and they always reflect the current top of the tree of the main 93branch. 94 95### Dependencies 96 97* A C++17 compiler. 98 (For MSVS: use 2019 or later.) 99* [CMake][cmake]: for generating compilation targets. 100* make: _Linux_, ninja is an alternative, if configured. 101* [Python 3.x][python]: for executing SPIRV-Tools scripts. (Optional if not using SPIRV-Tools and the 'External' subdirectory does not exist.) 102* [bison][bison]: _optional_, but needed when changing the grammar (glslang.y). 103* [googletest][googletest]: _optional_, but should use if making any changes to glslang. 104 105### Build steps 106 107The following steps assume a Bash shell. On Windows, that could be the Git Bash 108shell or some other shell of your choosing. 109 110#### 1) Check-Out this project 111 112```bash 113cd <parent of where you want glslang to be> 114git clone https://github.com/KhronosGroup/glslang.git 115``` 116 117#### 2) Check-Out External Projects 118 119```bash 120./update_glslang_sources.py 121``` 122 123#### 3) Configure 124 125Assume the source directory is `$SOURCE_DIR` and the build directory is 126`$BUILD_DIR`. First ensure the build directory exists, then navigate to it: 127 128```bash 129mkdir -p $BUILD_DIR 130cd $BUILD_DIR 131``` 132 133For building on Linux: 134 135```bash 136cmake -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX="$(pwd)/install" $SOURCE_DIR 137# "Release" (for CMAKE_BUILD_TYPE) could also be "Debug" or "RelWithDebInfo" 138``` 139 140For building on Android: 141```bash 142cmake $SOURCE_DIR -G "Unix Makefiles" -DCMAKE_INSTALL_PREFIX="$(pwd)/install" -DANDROID_ABI=arm64-v8a -DCMAKE_BUILD_TYPE=Release -DANDROID_STL=c++_static -DANDROID_PLATFORM=android-24 -DCMAKE_SYSTEM_NAME=Android -DANDROID_TOOLCHAIN=clang -DANDROID_ARM_MODE=arm -DCMAKE_MAKE_PROGRAM=$ANDROID_NDK_HOME/prebuilt/linux-x86_64/bin/make -DCMAKE_TOOLCHAIN_FILE=$ANDROID_NDK_HOME/build/cmake/android.toolchain.cmake 143# If on Windows will be -DCMAKE_MAKE_PROGRAM=%ANDROID_NDK_HOME%\prebuilt\windows-x86_64\bin\make.exe 144# -G is needed for building on Windows 145# -DANDROID_ABI can also be armeabi-v7a for 32 bit 146``` 147 148For building on Windows: 149 150```bash 151cmake $SOURCE_DIR -DCMAKE_INSTALL_PREFIX="$(pwd)/install" 152# The CMAKE_INSTALL_PREFIX part is for testing (explained later). 153``` 154 155The CMake GUI also works for Windows (version 3.4.1 tested). 156 157Also, consider using `git config --global core.fileMode false` (or with `--local`) on Windows 158to prevent the addition of execution permission on files. 159 160#### 4) Build and Install 161 162```bash 163# for Linux: 164make -j4 install 165 166# for Windows: 167cmake --build . --config Release --target install 168# "Release" (for --config) could also be "Debug", "MinSizeRel", or "RelWithDebInfo" 169``` 170 171If using MSVC, after running CMake to configure, use the 172Configuration Manager to check the `INSTALL` project. 173 174If you want to enable testing via CMake set `GLSLANG_TESTS=ON` when configuring the build. 175 176`GLSLANG_TESTS` is off by default to streamline the packaging / Vulkan SDK process. 177 178### Building (GN) 179 180glslang can also be built with the [GN build system](https://gn.googlesource.com/gn/). 181 182#### 1) Install `depot_tools` 183 184Download [depot_tools.zip](https://storage.googleapis.com/chrome-infra/depot_tools.zip), 185extract to a directory, and add this directory to your `PATH`. 186 187#### 2) Synchronize dependencies and generate build files 188 189This only needs to be done once after updating `glslang`. 190 191With the current directory set to your `glslang` checkout, type: 192 193```bash 194./update_glslang_sources.py 195gclient sync --gclientfile=standalone.gclient 196gn gen out/Default 197``` 198 199#### 3) Build 200 201With the current directory set to your `glslang` checkout, type: 202 203```bash 204cd out/Default 205ninja 206``` 207 208### If you need to change the GLSL grammar 209 210The grammar in `glslang/MachineIndependent/glslang.y` has to be recompiled with 211bison if it changes, the output files are committed to the repo to avoid every 212developer needing to have bison configured to compile the project when grammar 213changes are quite infrequent. For windows you can get binaries from 214[GnuWin32][bison-gnu-win32]. 215 216The command to rebuild is: 217 218```bash 219bison --defines=MachineIndependent/glslang_tab.cpp.h 220 -t MachineIndependent/glslang.y 221 -o MachineIndependent/glslang_tab.cpp 222``` 223 224The above command is also available in the bash script in `updateGrammar`, 225when executed from the glslang subdirectory of the glslang repository. 226 227### Building to WASM for the Web and Node 228### Building a standalone JS/WASM library for the Web and Node 229 230Use the steps in [Build Steps](#build-steps), with the following notes/exceptions: 231* `emsdk` needs to be present in your executable search path, *PATH* for 232 Bash-like environments: 233 + [Instructions located here](https://emscripten.org/docs/getting_started/downloads.html#sdk-download-and-install) 234* Wrap cmake call: `emcmake cmake` 235* Set `-DENABLE_OPT=OFF`. 236* Set `-DENABLE_HLSL=OFF` if HLSL is not needed. 237* For a standalone JS/WASM library, turn on `-DENABLE_GLSLANG_JS=ON`. 238* To get a fully minimized build, make sure to use `brotli` to compress the .js 239 and .wasm files 240 241Example: 242 243```sh 244emcmake cmake -DCMAKE_BUILD_TYPE=Release -DENABLE_GLSLANG_JS=ON \ 245 -DENABLE_HLSL=OFF -DENABLE_OPT=OFF .. 246``` 247 248## Building glslang - Using vcpkg 249 250You can download and install glslang using the [vcpkg](https://github.com/Microsoft/vcpkg) dependency manager: 251 252 git clone https://github.com/Microsoft/vcpkg.git 253 cd vcpkg 254 ./bootstrap-vcpkg.sh 255 ./vcpkg integrate install 256 ./vcpkg install glslang 257 258The glslang port in vcpkg is kept up to date by Microsoft team members and community contributors. If the version is out of date, please [create an issue or pull request](https://github.com/Microsoft/vcpkg) on the vcpkg repository. 259 260## Testing 261 262Right now, there are two test harnesses existing in glslang: one is [Google 263Test](gtests/), one is the [`runtests` script](Test/runtests). The former 264runs unit tests and single-shader single-threaded integration tests, while 265the latter runs multiple-shader linking tests and multi-threaded tests. 266 267### Running tests 268 269The [`runtests` script](Test/runtests) requires compiled binaries to be 270installed into `$BUILD_DIR/install`. Please make sure you have supplied the 271correct configuration to CMake (using `-DCMAKE_INSTALL_PREFIX`) when building; 272otherwise, you may want to modify the path in the `runtests` script. 273 274Running Google Test-backed tests: 275 276```bash 277cd $BUILD_DIR 278 279# for Linux: 280ctest 281 282# for Windows: 283ctest -C {Debug|Release|RelWithDebInfo|MinSizeRel} 284 285# or, run the test binary directly 286# (which gives more fine-grained control like filtering): 287<dir-to-glslangtests-in-build-dir>/glslangtests 288``` 289 290Running `runtests` script-backed tests: 291 292```bash 293cd $SOURCE_DIR/Test && ./runtests 294``` 295 296If some tests fail with validation errors, there may be a mismatch between the 297version of `spirv-val` on the system and the version of glslang. In this 298case, it is necessary to run `update_glslang_sources.py`. See "Check-Out 299External Projects" above for more details. 300 301### Contributing tests 302 303Test results should always be included with a pull request that modifies 304functionality. 305 306If you are writing unit tests, please use the Google Test framework and 307place the tests under the `gtests/` directory. 308 309Integration tests are placed in the `Test/` directory. It contains test input 310and a subdirectory `baseResults/` that contains the expected results of the 311tests. Both the tests and `baseResults/` are under source-code control. 312 313Google Test runs those integration tests by reading the test input, compiling 314them, and then compare against the expected results in `baseResults/`. The 315integration tests to run via Google Test is registered in various 316`gtests/*.FromFile.cpp` source files. `glslangtests` provides a command-line 317option `--update-mode`, which, if supplied, will overwrite the golden files 318under the `baseResults/` directory with real output from that invocation. 319For more information, please check `gtests/` directory's 320[README](gtests/README.md). 321 322For the `runtests` script, it will generate current results in the 323`localResults/` directory and `diff` them against the `baseResults/`. 324When you want to update the tracked test results, they need to be 325copied from `localResults/` to `baseResults/`. This can be done by 326the `bump` shell script. 327 328You can add your own private list of tests, not tracked publicly, by using 329`localtestlist` to list non-tracked tests. This is automatically read 330by `runtests` and included in the `diff` and `bump` process. 331 332## Programmatic Interfaces 333 334Another piece of software can programmatically translate shaders to an AST 335using one of two different interfaces: 336* A new C++ class-oriented interface, or 337* The original C functional interface 338 339The `main()` in `StandAlone/StandAlone.cpp` shows examples using both styles. 340 341### C++ Class Interface (new, preferred) 342 343This interface is in roughly the last 1/3 of `ShaderLang.h`. It is in the 344glslang namespace and contains the following, here with suggested calls 345for generating SPIR-V: 346 347```cxx 348const char* GetEsslVersionString(); 349const char* GetGlslVersionString(); 350bool InitializeProcess(); 351void FinalizeProcess(); 352 353class TShader 354 setStrings(...); 355 setEnvInput(EShSourceHlsl or EShSourceGlsl, stage, EShClientVulkan or EShClientOpenGL, 100); 356 setEnvClient(EShClientVulkan or EShClientOpenGL, EShTargetVulkan_1_0 or EShTargetVulkan_1_1 or EShTargetOpenGL_450); 357 setEnvTarget(EShTargetSpv, EShTargetSpv_1_0 or EShTargetSpv_1_3); 358 bool parse(...); 359 const char* getInfoLog(); 360 361class TProgram 362 void addShader(...); 363 bool link(...); 364 const char* getInfoLog(); 365 Reflection queries 366``` 367 368For just validating (not generating code), substitute these calls: 369 370```cxx 371 setEnvInput(EShSourceHlsl or EShSourceGlsl, stage, EShClientNone, 0); 372 setEnvClient(EShClientNone, 0); 373 setEnvTarget(EShTargetNone, 0); 374``` 375 376See `ShaderLang.h` and the usage of it in `StandAlone/StandAlone.cpp` for more 377details. There is a block comment giving more detail above the calls for 378`setEnvInput, setEnvClient, and setEnvTarget`. 379 380### C Functional Interface (original) 381 382This interface is in roughly the first 2/3 of `ShaderLang.h`, and referred to 383as the `Sh*()` interface, as all the entry points start `Sh`. 384 385The `Sh*()` interface takes a "compiler" call-back object, which it calls after 386building call back that is passed the AST and can then execute a back end on it. 387 388The following is a simplified resulting run-time call stack: 389 390```c 391ShCompile(shader, compiler) -> compiler(AST) -> <back end> 392``` 393 394In practice, `ShCompile()` takes shader strings, default version, and 395warning/error and other options for controlling compilation. 396 397### C Functional Interface (new) 398 399This interface is located `glslang_c_interface.h` and exposes functionality similar to the C++ interface. The following snippet is a complete example showing how to compile GLSL into SPIR-V 1.5 for Vulkan 1.2. 400 401```c 402#include <glslang/Include/glslang_c_interface.h> 403 404// Required for use of glslang_default_resource 405#include <glslang/Public/resource_limits_c.h> 406 407typedef struct SpirVBinary { 408 uint32_t *words; // SPIR-V words 409 int size; // number of words in SPIR-V binary 410} SpirVBinary; 411 412SpirVBinary compileShaderToSPIRV_Vulkan(glslang_stage_t stage, const char* shaderSource, const char* fileName) { 413 const glslang_input_t input = { 414 .language = GLSLANG_SOURCE_GLSL, 415 .stage = stage, 416 .client = GLSLANG_CLIENT_VULKAN, 417 .client_version = GLSLANG_TARGET_VULKAN_1_2, 418 .target_language = GLSLANG_TARGET_SPV, 419 .target_language_version = GLSLANG_TARGET_SPV_1_5, 420 .code = shaderSource, 421 .default_version = 100, 422 .default_profile = GLSLANG_NO_PROFILE, 423 .force_default_version_and_profile = false, 424 .forward_compatible = false, 425 .messages = GLSLANG_MSG_DEFAULT_BIT, 426 .resource = glslang_default_resource(), 427 }; 428 429 glslang_shader_t* shader = glslang_shader_create(&input); 430 431 SpirVBinary bin = { 432 .words = NULL, 433 .size = 0, 434 }; 435 if (!glslang_shader_preprocess(shader, &input)) { 436 printf("GLSL preprocessing failed %s\n", fileName); 437 printf("%s\n", glslang_shader_get_info_log(shader)); 438 printf("%s\n", glslang_shader_get_info_debug_log(shader)); 439 printf("%s\n", input.code); 440 glslang_shader_delete(shader); 441 return bin; 442 } 443 444 if (!glslang_shader_parse(shader, &input)) { 445 printf("GLSL parsing failed %s\n", fileName); 446 printf("%s\n", glslang_shader_get_info_log(shader)); 447 printf("%s\n", glslang_shader_get_info_debug_log(shader)); 448 printf("%s\n", glslang_shader_get_preprocessed_code(shader)); 449 glslang_shader_delete(shader); 450 return bin; 451 } 452 453 glslang_program_t* program = glslang_program_create(); 454 glslang_program_add_shader(program, shader); 455 456 if (!glslang_program_link(program, GLSLANG_MSG_SPV_RULES_BIT | GLSLANG_MSG_VULKAN_RULES_BIT)) { 457 printf("GLSL linking failed %s\n", fileName); 458 printf("%s\n", glslang_program_get_info_log(program)); 459 printf("%s\n", glslang_program_get_info_debug_log(program)); 460 glslang_program_delete(program); 461 glslang_shader_delete(shader); 462 return bin; 463 } 464 465 glslang_program_SPIRV_generate(program, stage); 466 467 bin.size = glslang_program_SPIRV_get_size(program); 468 bin.words = malloc(bin.size * sizeof(uint32_t)); 469 glslang_program_SPIRV_get(program, bin.words); 470 471 const char* spirv_messages = glslang_program_SPIRV_get_messages(program); 472 if (spirv_messages) 473 printf("(%s) %s\b", fileName, spirv_messages); 474 475 glslang_program_delete(program); 476 glslang_shader_delete(shader); 477 478 return bin; 479} 480``` 481 482## Basic Internal Operation 483 484* Initial lexical analysis is done by the preprocessor in 485 `MachineIndependent/Preprocessor`, and then refined by a GLSL scanner 486 in `MachineIndependent/Scan.cpp`. There is currently no use of flex. 487 488* Code is parsed using bison on `MachineIndependent/glslang.y` with the 489 aid of a symbol table and an AST. The symbol table is not passed on to 490 the back-end; the intermediate representation stands on its own. 491 The tree is built by the grammar productions, many of which are 492 offloaded into `ParseHelper.cpp`, and by `Intermediate.cpp`. 493 494* The intermediate representation is very high-level, and represented 495 as an in-memory tree. This serves to lose no information from the 496 original program, and to have efficient transfer of the result from 497 parsing to the back-end. In the AST, constants are propagated and 498 folded, and a very small amount of dead code is eliminated. 499 500 To aid linking and reflection, the last top-level branch in the AST 501 lists all global symbols. 502 503* The primary algorithm of the back-end compiler is to traverse the 504 tree (high-level intermediate representation), and create an internal 505 object code representation. There is an example of how to do this 506 in `MachineIndependent/intermOut.cpp`. 507 508* Reduction of the tree to a linear byte-code style low-level intermediate 509 representation is likely a good way to generate fully optimized code. 510 511* There is currently some dead old-style linker-type code still lying around. 512 513* Memory pool: parsing uses types derived from C++ `std` types, using a 514 custom allocator that puts them in a memory pool. This makes allocation 515 of individual container/contents just few cycles and deallocation free. 516 This pool is popped after the AST is made and processed. 517 518 The use is simple: if you are going to call `new`, there are three cases: 519 520 - the object comes from the pool (its base class has the macro 521 `POOL_ALLOCATOR_NEW_DELETE` in it) and you do not have to call `delete` 522 523 - it is a `TString`, in which case call `NewPoolTString()`, which gets 524 it from the pool, and there is no corresponding `delete` 525 526 - the object does not come from the pool, and you have to do normal 527 C++ memory management of what you `new` 528 529* Features can be protected by version/extension/stage/profile: 530 See the comment in `glslang/MachineIndependent/Versions.cpp`. 531 532[cmake]: https://cmake.org/ 533[python]: https://www.python.org/ 534[bison]: https://www.gnu.org/software/bison/ 535[googletest]: https://github.com/google/googletest 536[bison-gnu-win32]: http://gnuwin32.sourceforge.net/packages/bison.htm 537[main-tot-release]: https://github.com/KhronosGroup/glslang/releases/tag/main-tot 538