StandAlone.cpp 72 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771
  1. //
  2. // Copyright (C) 2002-2005 3Dlabs Inc. Ltd.
  3. // Copyright (C) 2013-2016 LunarG, Inc.
  4. // Copyright (C) 2016-2020 Google, Inc.
  5. //
  6. // All rights reserved.
  7. //
  8. // Redistribution and use in source and binary forms, with or without
  9. // modification, are permitted provided that the following conditions
  10. // are met:
  11. //
  12. // Redistributions of source code must retain the above copyright
  13. // notice, this list of conditions and the following disclaimer.
  14. //
  15. // Redistributions in binary form must reproduce the above
  16. // copyright notice, this list of conditions and the following
  17. // disclaimer in the documentation and/or other materials provided
  18. // with the distribution.
  19. //
  20. // Neither the name of 3Dlabs Inc. Ltd. nor the names of its
  21. // contributors may be used to endorse or promote products derived
  22. // from this software without specific prior written permission.
  23. //
  24. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  25. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  26. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
  27. // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
  28. // COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
  29. // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
  30. // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  31. // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  32. // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  33. // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
  34. // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  35. // POSSIBILITY OF SUCH DAMAGE.
  36. //
  37. // this only applies to the standalone wrapper, not the front end in general
  38. #ifndef _CRT_SECURE_NO_WARNINGS
  39. #define _CRT_SECURE_NO_WARNINGS
  40. #endif
  41. #include "ResourceLimits.h"
  42. #include "Worklist.h"
  43. #include "DirStackFileIncluder.h"
  44. #include "./../glslang/Include/ShHandle.h"
  45. #include "./../glslang/Public/ShaderLang.h"
  46. #include "../SPIRV/GlslangToSpv.h"
  47. #include "../SPIRV/GLSL.std.450.h"
  48. #include "../SPIRV/doc.h"
  49. #include "../SPIRV/disassemble.h"
  50. #include <cstring>
  51. #include <cstdlib>
  52. #include <cctype>
  53. #include <cmath>
  54. #include <array>
  55. #include <map>
  56. #include <memory>
  57. #include <thread>
  58. #include "../glslang/OSDependent/osinclude.h"
  59. // Build-time generated includes
  60. #include "glslang/build_info.h"
  61. extern "C" {
  62. GLSLANG_EXPORT void ShOutputHtml();
  63. }
  64. // Command-line options
  65. enum TOptions {
  66. EOptionNone = 0,
  67. EOptionIntermediate = (1 << 0),
  68. EOptionSuppressInfolog = (1 << 1),
  69. EOptionMemoryLeakMode = (1 << 2),
  70. EOptionRelaxedErrors = (1 << 3),
  71. EOptionGiveWarnings = (1 << 4),
  72. EOptionLinkProgram = (1 << 5),
  73. EOptionMultiThreaded = (1 << 6),
  74. EOptionDumpConfig = (1 << 7),
  75. EOptionDumpReflection = (1 << 8),
  76. EOptionSuppressWarnings = (1 << 9),
  77. EOptionDumpVersions = (1 << 10),
  78. EOptionSpv = (1 << 11),
  79. EOptionHumanReadableSpv = (1 << 12),
  80. EOptionVulkanRules = (1 << 13),
  81. EOptionDefaultDesktop = (1 << 14),
  82. EOptionOutputPreprocessed = (1 << 15),
  83. EOptionOutputHexadecimal = (1 << 16),
  84. EOptionReadHlsl = (1 << 17),
  85. EOptionCascadingErrors = (1 << 18),
  86. EOptionAutoMapBindings = (1 << 19),
  87. EOptionFlattenUniformArrays = (1 << 20),
  88. EOptionNoStorageFormat = (1 << 21),
  89. EOptionKeepUncalled = (1 << 22),
  90. EOptionHlslOffsets = (1 << 23),
  91. EOptionHlslIoMapping = (1 << 24),
  92. EOptionAutoMapLocations = (1 << 25),
  93. EOptionDebug = (1 << 26),
  94. EOptionStdin = (1 << 27),
  95. EOptionOptimizeDisable = (1 << 28),
  96. EOptionOptimizeSize = (1 << 29),
  97. EOptionInvertY = (1 << 30),
  98. EOptionDumpBareVersion = (1 << 31),
  99. };
  100. bool targetHlslFunctionality1 = false;
  101. bool SpvToolsDisassembler = false;
  102. bool SpvToolsValidate = false;
  103. bool NaNClamp = false;
  104. bool stripDebugInfo = false;
  105. bool beQuiet = false;
  106. //
  107. // Return codes from main/exit().
  108. //
  109. enum TFailCode {
  110. ESuccess = 0,
  111. EFailUsage,
  112. EFailCompile,
  113. EFailLink,
  114. EFailCompilerCreate,
  115. EFailThreadCreate,
  116. EFailLinkerCreate
  117. };
  118. //
  119. // Forward declarations.
  120. //
  121. EShLanguage FindLanguage(const std::string& name, bool parseSuffix=true);
  122. void CompileFile(const char* fileName, ShHandle);
  123. void usage();
  124. char* ReadFileData(const char* fileName);
  125. void FreeFileData(char* data);
  126. void InfoLogMsg(const char* msg, const char* name, const int num);
  127. // Globally track if any compile or link failure.
  128. bool CompileFailed = false;
  129. bool LinkFailed = false;
  130. // array of unique places to leave the shader names and infologs for the asynchronous compiles
  131. std::vector<std::unique_ptr<glslang::TWorkItem>> WorkItems;
  132. TBuiltInResource Resources;
  133. std::string ConfigFile;
  134. //
  135. // Parse either a .conf file provided by the user or the default from glslang::DefaultTBuiltInResource
  136. //
  137. void ProcessConfigFile()
  138. {
  139. if (ConfigFile.size() == 0)
  140. Resources = glslang::DefaultTBuiltInResource;
  141. #ifndef GLSLANG_WEB
  142. else {
  143. char* configString = ReadFileData(ConfigFile.c_str());
  144. glslang::DecodeResourceLimits(&Resources, configString);
  145. FreeFileData(configString);
  146. }
  147. #endif
  148. }
  149. int ReflectOptions = EShReflectionDefault;
  150. int Options = 0;
  151. const char* ExecutableName = nullptr;
  152. const char* binaryFileName = nullptr;
  153. const char* entryPointName = nullptr;
  154. const char* sourceEntryPointName = nullptr;
  155. const char* shaderStageName = nullptr;
  156. const char* variableName = nullptr;
  157. bool HlslEnable16BitTypes = false;
  158. bool HlslDX9compatible = false;
  159. bool DumpBuiltinSymbols = false;
  160. std::vector<std::string> IncludeDirectoryList;
  161. // Source environment
  162. // (source 'Client' is currently the same as target 'Client')
  163. int ClientInputSemanticsVersion = 100;
  164. // Target environment
  165. glslang::EShClient Client = glslang::EShClientNone; // will stay EShClientNone if only validating
  166. glslang::EShTargetClientVersion ClientVersion; // not valid until Client is set
  167. glslang::EShTargetLanguage TargetLanguage = glslang::EShTargetNone;
  168. glslang::EShTargetLanguageVersion TargetVersion; // not valid until TargetLanguage is set
  169. std::vector<std::string> Processes; // what should be recorded by OpModuleProcessed, or equivalent
  170. // Per descriptor-set binding base data
  171. typedef std::map<unsigned int, unsigned int> TPerSetBaseBinding;
  172. std::vector<std::pair<std::string, int>> uniformLocationOverrides;
  173. int uniformBase = 0;
  174. std::array<std::array<unsigned int, EShLangCount>, glslang::EResCount> baseBinding;
  175. std::array<std::array<TPerSetBaseBinding, EShLangCount>, glslang::EResCount> baseBindingForSet;
  176. std::array<std::vector<std::string>, EShLangCount> baseResourceSetBinding;
  177. // Add things like "#define ..." to a preamble to use in the beginning of the shader.
  178. class TPreamble {
  179. public:
  180. TPreamble() { }
  181. bool isSet() const { return text.size() > 0; }
  182. const char* get() const { return text.c_str(); }
  183. // #define...
  184. void addDef(std::string def)
  185. {
  186. text.append("#define ");
  187. fixLine(def);
  188. Processes.push_back("define-macro ");
  189. Processes.back().append(def);
  190. // The first "=" needs to turn into a space
  191. const size_t equal = def.find_first_of("=");
  192. if (equal != def.npos)
  193. def[equal] = ' ';
  194. text.append(def);
  195. text.append("\n");
  196. }
  197. // #undef...
  198. void addUndef(std::string undef)
  199. {
  200. text.append("#undef ");
  201. fixLine(undef);
  202. Processes.push_back("undef-macro ");
  203. Processes.back().append(undef);
  204. text.append(undef);
  205. text.append("\n");
  206. }
  207. protected:
  208. void fixLine(std::string& line)
  209. {
  210. // Can't go past a newline in the line
  211. const size_t end = line.find_first_of("\n");
  212. if (end != line.npos)
  213. line = line.substr(0, end);
  214. }
  215. std::string text; // contents of preamble
  216. };
  217. // Track the user's #define and #undef from the command line.
  218. TPreamble UserPreamble;
  219. //
  220. // Create the default name for saving a binary if -o is not provided.
  221. //
  222. const char* GetBinaryName(EShLanguage stage)
  223. {
  224. const char* name;
  225. if (binaryFileName == nullptr) {
  226. switch (stage) {
  227. case EShLangVertex: name = "vert.spv"; break;
  228. case EShLangTessControl: name = "tesc.spv"; break;
  229. case EShLangTessEvaluation: name = "tese.spv"; break;
  230. case EShLangGeometry: name = "geom.spv"; break;
  231. case EShLangFragment: name = "frag.spv"; break;
  232. case EShLangCompute: name = "comp.spv"; break;
  233. case EShLangRayGen: name = "rgen.spv"; break;
  234. case EShLangIntersect: name = "rint.spv"; break;
  235. case EShLangAnyHit: name = "rahit.spv"; break;
  236. case EShLangClosestHit: name = "rchit.spv"; break;
  237. case EShLangMiss: name = "rmiss.spv"; break;
  238. case EShLangCallable: name = "rcall.spv"; break;
  239. case EShLangMeshNV: name = "mesh.spv"; break;
  240. case EShLangTaskNV: name = "task.spv"; break;
  241. default: name = "unknown"; break;
  242. }
  243. } else
  244. name = binaryFileName;
  245. return name;
  246. }
  247. //
  248. // *.conf => this is a config file that can set limits/resources
  249. //
  250. bool SetConfigFile(const std::string& name)
  251. {
  252. if (name.size() < 5)
  253. return false;
  254. if (name.compare(name.size() - 5, 5, ".conf") == 0) {
  255. ConfigFile = name;
  256. return true;
  257. }
  258. return false;
  259. }
  260. //
  261. // Give error and exit with failure code.
  262. //
  263. void Error(const char* message, const char* detail = nullptr)
  264. {
  265. fprintf(stderr, "%s: Error: ", ExecutableName);
  266. if (detail != nullptr)
  267. fprintf(stderr, "%s: ", detail);
  268. fprintf(stderr, "%s (use -h for usage)\n", message);
  269. exit(EFailUsage);
  270. }
  271. //
  272. // Process an optional binding base of one the forms:
  273. // --argname [stage] base // base for stage (if given) or all stages (if not)
  274. // --argname [stage] [base set]... // set/base pairs: set the base for given binding set.
  275. // Where stage is one of the forms accepted by FindLanguage, and base is an integer
  276. //
  277. void ProcessBindingBase(int& argc, char**& argv, glslang::TResourceType res)
  278. {
  279. if (argc < 2)
  280. usage();
  281. EShLanguage lang = EShLangCount;
  282. int singleBase = 0;
  283. TPerSetBaseBinding perSetBase;
  284. int arg = 1;
  285. // Parse stage, if given
  286. if (!isdigit(argv[arg][0])) {
  287. if (argc < 3) // this form needs one more argument
  288. usage();
  289. lang = FindLanguage(argv[arg++], false);
  290. }
  291. if ((argc - arg) > 2 && isdigit(argv[arg+0][0]) && isdigit(argv[arg+1][0])) {
  292. // Parse a per-set binding base
  293. while ((argc - arg) > 2 && isdigit(argv[arg+0][0]) && isdigit(argv[arg+1][0])) {
  294. const int baseNum = atoi(argv[arg++]);
  295. const int setNum = atoi(argv[arg++]);
  296. perSetBase[setNum] = baseNum;
  297. }
  298. } else {
  299. // Parse single binding base
  300. singleBase = atoi(argv[arg++]);
  301. }
  302. argc -= (arg-1);
  303. argv += (arg-1);
  304. // Set one or all languages
  305. const int langMin = (lang < EShLangCount) ? lang+0 : 0;
  306. const int langMax = (lang < EShLangCount) ? lang+1 : EShLangCount;
  307. for (int lang = langMin; lang < langMax; ++lang) {
  308. if (!perSetBase.empty())
  309. baseBindingForSet[res][lang].insert(perSetBase.begin(), perSetBase.end());
  310. else
  311. baseBinding[res][lang] = singleBase;
  312. }
  313. }
  314. void ProcessResourceSetBindingBase(int& argc, char**& argv, std::array<std::vector<std::string>, EShLangCount>& base)
  315. {
  316. if (argc < 2)
  317. usage();
  318. if (!isdigit(argv[1][0])) {
  319. if (argc < 3) // this form needs one more argument
  320. usage();
  321. // Parse form: --argname stage [regname set base...], or:
  322. // --argname stage set
  323. const EShLanguage lang = FindLanguage(argv[1], false);
  324. argc--;
  325. argv++;
  326. while (argc > 1 && argv[1] != nullptr && argv[1][0] != '-') {
  327. base[lang].push_back(argv[1]);
  328. argc--;
  329. argv++;
  330. }
  331. // Must have one arg, or a multiple of three (for [regname set binding] triples)
  332. if (base[lang].size() != 1 && (base[lang].size() % 3) != 0)
  333. usage();
  334. } else {
  335. // Parse form: --argname set
  336. for (int lang=0; lang<EShLangCount; ++lang)
  337. base[lang].push_back(argv[1]);
  338. argc--;
  339. argv++;
  340. }
  341. }
  342. //
  343. // Do all command-line argument parsing. This includes building up the work-items
  344. // to be processed later, and saving all the command-line options.
  345. //
  346. // Does not return (it exits) if command-line is fatally flawed.
  347. //
  348. void ProcessArguments(std::vector<std::unique_ptr<glslang::TWorkItem>>& workItems, int argc, char* argv[])
  349. {
  350. for (int res = 0; res < glslang::EResCount; ++res)
  351. baseBinding[res].fill(0);
  352. ExecutableName = argv[0];
  353. workItems.reserve(argc);
  354. const auto bumpArg = [&]() {
  355. if (argc > 0) {
  356. argc--;
  357. argv++;
  358. }
  359. };
  360. // read a string directly attached to a single-letter option
  361. const auto getStringOperand = [&](const char* desc) {
  362. if (argv[0][2] == 0) {
  363. printf("%s must immediately follow option (no spaces)\n", desc);
  364. exit(EFailUsage);
  365. }
  366. return argv[0] + 2;
  367. };
  368. // read a number attached to a single-letter option
  369. const auto getAttachedNumber = [&](const char* desc) {
  370. int num = atoi(argv[0] + 2);
  371. if (num == 0) {
  372. printf("%s: expected attached non-0 number\n", desc);
  373. exit(EFailUsage);
  374. }
  375. return num;
  376. };
  377. // minimum needed (without overriding something else) to target Vulkan SPIR-V
  378. const auto setVulkanSpv = []() {
  379. if (Client == glslang::EShClientNone)
  380. ClientVersion = glslang::EShTargetVulkan_1_0;
  381. Client = glslang::EShClientVulkan;
  382. Options |= EOptionSpv;
  383. Options |= EOptionVulkanRules;
  384. Options |= EOptionLinkProgram;
  385. };
  386. // minimum needed (without overriding something else) to target OpenGL SPIR-V
  387. const auto setOpenGlSpv = []() {
  388. if (Client == glslang::EShClientNone)
  389. ClientVersion = glslang::EShTargetOpenGL_450;
  390. Client = glslang::EShClientOpenGL;
  391. Options |= EOptionSpv;
  392. Options |= EOptionLinkProgram;
  393. // undo a -H default to Vulkan
  394. Options &= ~EOptionVulkanRules;
  395. };
  396. const auto getUniformOverride = [getStringOperand]() {
  397. const char *arg = getStringOperand("-u<name>:<location>");
  398. const char *split = strchr(arg, ':');
  399. if (split == NULL) {
  400. printf("%s: missing location\n", arg);
  401. exit(EFailUsage);
  402. }
  403. errno = 0;
  404. int location = ::strtol(split + 1, NULL, 10);
  405. if (errno) {
  406. printf("%s: invalid location\n", arg);
  407. exit(EFailUsage);
  408. }
  409. return std::make_pair(std::string(arg, split - arg), location);
  410. };
  411. for (bumpArg(); argc >= 1; bumpArg()) {
  412. if (argv[0][0] == '-') {
  413. switch (argv[0][1]) {
  414. case '-':
  415. {
  416. std::string lowerword(argv[0]+2);
  417. std::transform(lowerword.begin(), lowerword.end(), lowerword.begin(), ::tolower);
  418. // handle --word style options
  419. if (lowerword == "auto-map-bindings" || // synonyms
  420. lowerword == "auto-map-binding" ||
  421. lowerword == "amb") {
  422. Options |= EOptionAutoMapBindings;
  423. } else if (lowerword == "auto-map-locations" || // synonyms
  424. lowerword == "aml") {
  425. Options |= EOptionAutoMapLocations;
  426. } else if (lowerword == "uniform-base") {
  427. if (argc <= 1)
  428. Error("no <base> provided", lowerword.c_str());
  429. uniformBase = ::strtol(argv[1], NULL, 10);
  430. bumpArg();
  431. break;
  432. } else if (lowerword == "client") {
  433. if (argc > 1) {
  434. if (strcmp(argv[1], "vulkan100") == 0)
  435. setVulkanSpv();
  436. else if (strcmp(argv[1], "opengl100") == 0)
  437. setOpenGlSpv();
  438. else
  439. Error("expects vulkan100 or opengl100", lowerword.c_str());
  440. } else
  441. Error("expects vulkan100 or opengl100", lowerword.c_str());
  442. bumpArg();
  443. } else if (lowerword == "define-macro" ||
  444. lowerword == "d") {
  445. if (argc > 1)
  446. UserPreamble.addDef(argv[1]);
  447. else
  448. Error("expects <name[=def]>", argv[0]);
  449. bumpArg();
  450. } else if (lowerword == "dump-builtin-symbols") {
  451. DumpBuiltinSymbols = true;
  452. } else if (lowerword == "entry-point") {
  453. entryPointName = argv[1];
  454. if (argc <= 1)
  455. Error("no <name> provided", lowerword.c_str());
  456. bumpArg();
  457. } else if (lowerword == "flatten-uniform-arrays" || // synonyms
  458. lowerword == "flatten-uniform-array" ||
  459. lowerword == "fua") {
  460. Options |= EOptionFlattenUniformArrays;
  461. } else if (lowerword == "hlsl-offsets") {
  462. Options |= EOptionHlslOffsets;
  463. } else if (lowerword == "hlsl-iomap" ||
  464. lowerword == "hlsl-iomapper" ||
  465. lowerword == "hlsl-iomapping") {
  466. Options |= EOptionHlslIoMapping;
  467. } else if (lowerword == "hlsl-enable-16bit-types") {
  468. HlslEnable16BitTypes = true;
  469. } else if (lowerword == "hlsl-dx9-compatible") {
  470. HlslDX9compatible = true;
  471. } else if (lowerword == "invert-y" || // synonyms
  472. lowerword == "iy") {
  473. Options |= EOptionInvertY;
  474. } else if (lowerword == "keep-uncalled" || // synonyms
  475. lowerword == "ku") {
  476. Options |= EOptionKeepUncalled;
  477. } else if (lowerword == "nan-clamp") {
  478. NaNClamp = true;
  479. } else if (lowerword == "no-storage-format" || // synonyms
  480. lowerword == "nsf") {
  481. Options |= EOptionNoStorageFormat;
  482. } else if (lowerword == "relaxed-errors") {
  483. Options |= EOptionRelaxedErrors;
  484. } else if (lowerword == "reflect-strict-array-suffix") {
  485. ReflectOptions |= EShReflectionStrictArraySuffix;
  486. } else if (lowerword == "reflect-basic-array-suffix") {
  487. ReflectOptions |= EShReflectionBasicArraySuffix;
  488. } else if (lowerword == "reflect-intermediate-io") {
  489. ReflectOptions |= EShReflectionIntermediateIO;
  490. } else if (lowerword == "reflect-separate-buffers") {
  491. ReflectOptions |= EShReflectionSeparateBuffers;
  492. } else if (lowerword == "reflect-all-block-variables") {
  493. ReflectOptions |= EShReflectionAllBlockVariables;
  494. } else if (lowerword == "reflect-unwrap-io-blocks") {
  495. ReflectOptions |= EShReflectionUnwrapIOBlocks;
  496. } else if (lowerword == "reflect-all-io-variables") {
  497. ReflectOptions |= EShReflectionAllIOVariables;
  498. } else if (lowerword == "reflect-shared-std140-ubo") {
  499. ReflectOptions |= EShReflectionSharedStd140UBO;
  500. } else if (lowerword == "reflect-shared-std140-ssbo") {
  501. ReflectOptions |= EShReflectionSharedStd140SSBO;
  502. } else if (lowerword == "resource-set-bindings" || // synonyms
  503. lowerword == "resource-set-binding" ||
  504. lowerword == "rsb") {
  505. ProcessResourceSetBindingBase(argc, argv, baseResourceSetBinding);
  506. } else if (lowerword == "shift-image-bindings" || // synonyms
  507. lowerword == "shift-image-binding" ||
  508. lowerword == "sib") {
  509. ProcessBindingBase(argc, argv, glslang::EResImage);
  510. } else if (lowerword == "shift-sampler-bindings" || // synonyms
  511. lowerword == "shift-sampler-binding" ||
  512. lowerword == "ssb") {
  513. ProcessBindingBase(argc, argv, glslang::EResSampler);
  514. } else if (lowerword == "shift-uav-bindings" || // synonyms
  515. lowerword == "shift-uav-binding" ||
  516. lowerword == "suavb") {
  517. ProcessBindingBase(argc, argv, glslang::EResUav);
  518. } else if (lowerword == "shift-texture-bindings" || // synonyms
  519. lowerword == "shift-texture-binding" ||
  520. lowerword == "stb") {
  521. ProcessBindingBase(argc, argv, glslang::EResTexture);
  522. } else if (lowerword == "shift-ubo-bindings" || // synonyms
  523. lowerword == "shift-ubo-binding" ||
  524. lowerword == "shift-cbuffer-bindings" ||
  525. lowerword == "shift-cbuffer-binding" ||
  526. lowerword == "sub" ||
  527. lowerword == "scb") {
  528. ProcessBindingBase(argc, argv, glslang::EResUbo);
  529. } else if (lowerword == "shift-ssbo-bindings" || // synonyms
  530. lowerword == "shift-ssbo-binding" ||
  531. lowerword == "sbb") {
  532. ProcessBindingBase(argc, argv, glslang::EResSsbo);
  533. } else if (lowerword == "source-entrypoint" || // synonyms
  534. lowerword == "sep") {
  535. if (argc <= 1)
  536. Error("no <entry-point> provided", lowerword.c_str());
  537. sourceEntryPointName = argv[1];
  538. bumpArg();
  539. break;
  540. } else if (lowerword == "spirv-dis") {
  541. SpvToolsDisassembler = true;
  542. } else if (lowerword == "spirv-val") {
  543. SpvToolsValidate = true;
  544. } else if (lowerword == "stdin") {
  545. Options |= EOptionStdin;
  546. shaderStageName = argv[1];
  547. } else if (lowerword == "suppress-warnings") {
  548. Options |= EOptionSuppressWarnings;
  549. } else if (lowerword == "target-env") {
  550. if (argc > 1) {
  551. if (strcmp(argv[1], "vulkan1.0") == 0) {
  552. setVulkanSpv();
  553. ClientVersion = glslang::EShTargetVulkan_1_0;
  554. } else if (strcmp(argv[1], "vulkan1.1") == 0) {
  555. setVulkanSpv();
  556. ClientVersion = glslang::EShTargetVulkan_1_1;
  557. } else if (strcmp(argv[1], "vulkan1.2") == 0) {
  558. setVulkanSpv();
  559. ClientVersion = glslang::EShTargetVulkan_1_2;
  560. } else if (strcmp(argv[1], "opengl") == 0) {
  561. setOpenGlSpv();
  562. ClientVersion = glslang::EShTargetOpenGL_450;
  563. } else if (strcmp(argv[1], "spirv1.0") == 0) {
  564. TargetLanguage = glslang::EShTargetSpv;
  565. TargetVersion = glslang::EShTargetSpv_1_0;
  566. } else if (strcmp(argv[1], "spirv1.1") == 0) {
  567. TargetLanguage = glslang::EShTargetSpv;
  568. TargetVersion = glslang::EShTargetSpv_1_1;
  569. } else if (strcmp(argv[1], "spirv1.2") == 0) {
  570. TargetLanguage = glslang::EShTargetSpv;
  571. TargetVersion = glslang::EShTargetSpv_1_2;
  572. } else if (strcmp(argv[1], "spirv1.3") == 0) {
  573. TargetLanguage = glslang::EShTargetSpv;
  574. TargetVersion = glslang::EShTargetSpv_1_3;
  575. } else if (strcmp(argv[1], "spirv1.4") == 0) {
  576. TargetLanguage = glslang::EShTargetSpv;
  577. TargetVersion = glslang::EShTargetSpv_1_4;
  578. } else if (strcmp(argv[1], "spirv1.5") == 0) {
  579. TargetLanguage = glslang::EShTargetSpv;
  580. TargetVersion = glslang::EShTargetSpv_1_5;
  581. } else
  582. Error("--target-env expected one of: vulkan1.0, vulkan1.1, vulkan1.2, opengl,\n"
  583. "spirv1.0, spirv1.1, spirv1.2, spirv1.3, spirv1.4, or spirv1.5");
  584. }
  585. bumpArg();
  586. } else if (lowerword == "undef-macro" ||
  587. lowerword == "u") {
  588. if (argc > 1)
  589. UserPreamble.addUndef(argv[1]);
  590. else
  591. Error("expects <name>", argv[0]);
  592. bumpArg();
  593. } else if (lowerword == "variable-name" || // synonyms
  594. lowerword == "vn") {
  595. Options |= EOptionOutputHexadecimal;
  596. if (argc <= 1)
  597. Error("no <C-variable-name> provided", lowerword.c_str());
  598. variableName = argv[1];
  599. bumpArg();
  600. break;
  601. } else if (lowerword == "quiet") {
  602. beQuiet = true;
  603. } else if (lowerword == "version") {
  604. Options |= EOptionDumpVersions;
  605. } else if (lowerword == "help") {
  606. usage();
  607. break;
  608. } else {
  609. Error("unrecognized command-line option", argv[0]);
  610. }
  611. }
  612. break;
  613. case 'C':
  614. Options |= EOptionCascadingErrors;
  615. break;
  616. case 'D':
  617. if (argv[0][2] == 0)
  618. Options |= EOptionReadHlsl;
  619. else
  620. UserPreamble.addDef(getStringOperand("-D<name[=def]>"));
  621. break;
  622. case 'u':
  623. uniformLocationOverrides.push_back(getUniformOverride());
  624. break;
  625. case 'E':
  626. Options |= EOptionOutputPreprocessed;
  627. break;
  628. case 'G':
  629. // OpenGL client
  630. setOpenGlSpv();
  631. if (argv[0][2] != 0)
  632. ClientInputSemanticsVersion = getAttachedNumber("-G<num> client input semantics");
  633. if (ClientInputSemanticsVersion != 100)
  634. Error("unknown client version for -G, should be 100");
  635. break;
  636. case 'H':
  637. Options |= EOptionHumanReadableSpv;
  638. if ((Options & EOptionSpv) == 0) {
  639. // default to Vulkan
  640. setVulkanSpv();
  641. }
  642. break;
  643. case 'I':
  644. IncludeDirectoryList.push_back(getStringOperand("-I<dir> include path"));
  645. break;
  646. case 'O':
  647. if (argv[0][2] == 'd')
  648. Options |= EOptionOptimizeDisable;
  649. else if (argv[0][2] == 's')
  650. #if ENABLE_OPT
  651. Options |= EOptionOptimizeSize;
  652. #else
  653. Error("-Os not available; optimizer not linked");
  654. #endif
  655. else
  656. Error("unknown -O option");
  657. break;
  658. case 'S':
  659. if (argc <= 1)
  660. Error("no <stage> specified for -S");
  661. shaderStageName = argv[1];
  662. bumpArg();
  663. break;
  664. case 'U':
  665. UserPreamble.addUndef(getStringOperand("-U<name>"));
  666. break;
  667. case 'V':
  668. setVulkanSpv();
  669. if (argv[0][2] != 0)
  670. ClientInputSemanticsVersion = getAttachedNumber("-V<num> client input semantics");
  671. if (ClientInputSemanticsVersion != 100)
  672. Error("unknown client version for -V, should be 100");
  673. break;
  674. case 'c':
  675. Options |= EOptionDumpConfig;
  676. break;
  677. case 'd':
  678. if (strncmp(&argv[0][1], "dumpversion", strlen(&argv[0][1]) + 1) == 0 ||
  679. strncmp(&argv[0][1], "dumpfullversion", strlen(&argv[0][1]) + 1) == 0)
  680. Options |= EOptionDumpBareVersion;
  681. else
  682. Options |= EOptionDefaultDesktop;
  683. break;
  684. case 'e':
  685. entryPointName = argv[1];
  686. if (argc <= 1)
  687. Error("no <name> provided for -e");
  688. bumpArg();
  689. break;
  690. case 'f':
  691. if (strcmp(&argv[0][2], "hlsl_functionality1") == 0)
  692. targetHlslFunctionality1 = true;
  693. else
  694. Error("-f: expected hlsl_functionality1");
  695. break;
  696. case 'g':
  697. // Override previous -g or -g0 argument
  698. stripDebugInfo = false;
  699. Options &= ~EOptionDebug;
  700. if (argv[0][2] == '0')
  701. stripDebugInfo = true;
  702. else
  703. Options |= EOptionDebug;
  704. break;
  705. case 'h':
  706. usage();
  707. break;
  708. case 'i':
  709. Options |= EOptionIntermediate;
  710. break;
  711. case 'l':
  712. Options |= EOptionLinkProgram;
  713. break;
  714. case 'm':
  715. Options |= EOptionMemoryLeakMode;
  716. break;
  717. case 'o':
  718. if (argc <= 1)
  719. Error("no <file> provided for -o");
  720. binaryFileName = argv[1];
  721. bumpArg();
  722. break;
  723. case 'q':
  724. Options |= EOptionDumpReflection;
  725. break;
  726. case 'r':
  727. Options |= EOptionRelaxedErrors;
  728. break;
  729. case 's':
  730. Options |= EOptionSuppressInfolog;
  731. break;
  732. case 't':
  733. Options |= EOptionMultiThreaded;
  734. break;
  735. case 'v':
  736. Options |= EOptionDumpVersions;
  737. break;
  738. case 'w':
  739. Options |= EOptionSuppressWarnings;
  740. break;
  741. case 'x':
  742. Options |= EOptionOutputHexadecimal;
  743. break;
  744. default:
  745. Error("unrecognized command-line option", argv[0]);
  746. break;
  747. }
  748. } else {
  749. std::string name(argv[0]);
  750. if (! SetConfigFile(name)) {
  751. workItems.push_back(std::unique_ptr<glslang::TWorkItem>(new glslang::TWorkItem(name)));
  752. }
  753. }
  754. }
  755. // Make sure that -S is always specified if --stdin is specified
  756. if ((Options & EOptionStdin) && shaderStageName == nullptr)
  757. Error("must provide -S when --stdin is given");
  758. // Make sure that -E is not specified alongside linking (which includes SPV generation)
  759. // Or things that require linking
  760. if (Options & EOptionOutputPreprocessed) {
  761. if (Options & EOptionLinkProgram)
  762. Error("can't use -E when linking is selected");
  763. if (Options & EOptionDumpReflection)
  764. Error("reflection requires linking, which can't be used when -E when is selected");
  765. }
  766. // reflection requires linking
  767. if ((Options & EOptionDumpReflection) && !(Options & EOptionLinkProgram))
  768. Error("reflection requires -l for linking");
  769. // -o or -x makes no sense if there is no target binary
  770. if (binaryFileName && (Options & EOptionSpv) == 0)
  771. Error("no binary generation requested (e.g., -V)");
  772. if ((Options & EOptionFlattenUniformArrays) != 0 &&
  773. (Options & EOptionReadHlsl) == 0)
  774. Error("uniform array flattening only valid when compiling HLSL source.");
  775. // rationalize client and target language
  776. if (TargetLanguage == glslang::EShTargetNone) {
  777. switch (ClientVersion) {
  778. case glslang::EShTargetVulkan_1_0:
  779. TargetLanguage = glslang::EShTargetSpv;
  780. TargetVersion = glslang::EShTargetSpv_1_0;
  781. break;
  782. case glslang::EShTargetVulkan_1_1:
  783. TargetLanguage = glslang::EShTargetSpv;
  784. TargetVersion = glslang::EShTargetSpv_1_3;
  785. break;
  786. case glslang::EShTargetVulkan_1_2:
  787. TargetLanguage = glslang::EShTargetSpv;
  788. TargetVersion = glslang::EShTargetSpv_1_5;
  789. break;
  790. case glslang::EShTargetOpenGL_450:
  791. TargetLanguage = glslang::EShTargetSpv;
  792. TargetVersion = glslang::EShTargetSpv_1_0;
  793. break;
  794. default:
  795. break;
  796. }
  797. }
  798. if (TargetLanguage != glslang::EShTargetNone && Client == glslang::EShClientNone)
  799. Error("To generate SPIR-V, also specify client semantics. See -G and -V.");
  800. }
  801. //
  802. // Translate the meaningful subset of command-line options to parser-behavior options.
  803. //
  804. void SetMessageOptions(EShMessages& messages)
  805. {
  806. if (Options & EOptionRelaxedErrors)
  807. messages = (EShMessages)(messages | EShMsgRelaxedErrors);
  808. if (Options & EOptionIntermediate)
  809. messages = (EShMessages)(messages | EShMsgAST);
  810. if (Options & EOptionSuppressWarnings)
  811. messages = (EShMessages)(messages | EShMsgSuppressWarnings);
  812. if (Options & EOptionSpv)
  813. messages = (EShMessages)(messages | EShMsgSpvRules);
  814. if (Options & EOptionVulkanRules)
  815. messages = (EShMessages)(messages | EShMsgVulkanRules);
  816. if (Options & EOptionOutputPreprocessed)
  817. messages = (EShMessages)(messages | EShMsgOnlyPreprocessor);
  818. if (Options & EOptionReadHlsl)
  819. messages = (EShMessages)(messages | EShMsgReadHlsl);
  820. if (Options & EOptionCascadingErrors)
  821. messages = (EShMessages)(messages | EShMsgCascadingErrors);
  822. if (Options & EOptionKeepUncalled)
  823. messages = (EShMessages)(messages | EShMsgKeepUncalled);
  824. if (Options & EOptionHlslOffsets)
  825. messages = (EShMessages)(messages | EShMsgHlslOffsets);
  826. if (Options & EOptionDebug)
  827. messages = (EShMessages)(messages | EShMsgDebugInfo);
  828. if (HlslEnable16BitTypes)
  829. messages = (EShMessages)(messages | EShMsgHlslEnable16BitTypes);
  830. if ((Options & EOptionOptimizeDisable) || !ENABLE_OPT)
  831. messages = (EShMessages)(messages | EShMsgHlslLegalization);
  832. if (HlslDX9compatible)
  833. messages = (EShMessages)(messages | EShMsgHlslDX9Compatible);
  834. if (DumpBuiltinSymbols)
  835. messages = (EShMessages)(messages | EShMsgBuiltinSymbolTable);
  836. }
  837. //
  838. // Thread entry point, for non-linking asynchronous mode.
  839. //
  840. void CompileShaders(glslang::TWorklist& worklist)
  841. {
  842. if (Options & EOptionDebug)
  843. Error("cannot generate debug information unless linking to generate code");
  844. glslang::TWorkItem* workItem;
  845. if (Options & EOptionStdin) {
  846. if (worklist.remove(workItem)) {
  847. ShHandle compiler = ShConstructCompiler(FindLanguage("stdin"), Options);
  848. if (compiler == nullptr)
  849. return;
  850. CompileFile("stdin", compiler);
  851. if (! (Options & EOptionSuppressInfolog))
  852. workItem->results = ShGetInfoLog(compiler);
  853. ShDestruct(compiler);
  854. }
  855. } else {
  856. while (worklist.remove(workItem)) {
  857. ShHandle compiler = ShConstructCompiler(FindLanguage(workItem->name), Options);
  858. if (compiler == 0)
  859. return;
  860. CompileFile(workItem->name.c_str(), compiler);
  861. if (! (Options & EOptionSuppressInfolog))
  862. workItem->results = ShGetInfoLog(compiler);
  863. ShDestruct(compiler);
  864. }
  865. }
  866. }
  867. // Outputs the given string, but only if it is non-null and non-empty.
  868. // This prevents erroneous newlines from appearing.
  869. void PutsIfNonEmpty(const char* str)
  870. {
  871. if (str && str[0]) {
  872. puts(str);
  873. }
  874. }
  875. // Outputs the given string to stderr, but only if it is non-null and non-empty.
  876. // This prevents erroneous newlines from appearing.
  877. void StderrIfNonEmpty(const char* str)
  878. {
  879. if (str && str[0])
  880. fprintf(stderr, "%s\n", str);
  881. }
  882. // Simple bundling of what makes a compilation unit for ease in passing around,
  883. // and separation of handling file IO versus API (programmatic) compilation.
  884. struct ShaderCompUnit {
  885. EShLanguage stage;
  886. static const int maxCount = 1;
  887. int count; // live number of strings/names
  888. const char* text[maxCount]; // memory owned/managed externally
  889. std::string fileName[maxCount]; // hold's the memory, but...
  890. const char* fileNameList[maxCount]; // downstream interface wants pointers
  891. ShaderCompUnit(EShLanguage stage) : stage(stage), count(0) { }
  892. ShaderCompUnit(const ShaderCompUnit& rhs)
  893. {
  894. stage = rhs.stage;
  895. count = rhs.count;
  896. for (int i = 0; i < count; ++i) {
  897. fileName[i] = rhs.fileName[i];
  898. text[i] = rhs.text[i];
  899. fileNameList[i] = rhs.fileName[i].c_str();
  900. }
  901. }
  902. void addString(std::string& ifileName, const char* itext)
  903. {
  904. assert(count < maxCount);
  905. fileName[count] = ifileName;
  906. text[count] = itext;
  907. fileNameList[count] = fileName[count].c_str();
  908. ++count;
  909. }
  910. };
  911. //
  912. // For linking mode: Will independently parse each compilation unit, but then put them
  913. // in the same program and link them together, making at most one linked module per
  914. // pipeline stage.
  915. //
  916. // Uses the new C++ interface instead of the old handle-based interface.
  917. //
  918. void CompileAndLinkShaderUnits(std::vector<ShaderCompUnit> compUnits)
  919. {
  920. // keep track of what to free
  921. std::list<glslang::TShader*> shaders;
  922. EShMessages messages = EShMsgDefault;
  923. SetMessageOptions(messages);
  924. //
  925. // Per-shader processing...
  926. //
  927. glslang::TProgram& program = *new glslang::TProgram;
  928. for (auto it = compUnits.cbegin(); it != compUnits.cend(); ++it) {
  929. const auto &compUnit = *it;
  930. glslang::TShader* shader = new glslang::TShader(compUnit.stage);
  931. shader->setStringsWithLengthsAndNames(compUnit.text, NULL, compUnit.fileNameList, compUnit.count);
  932. if (entryPointName)
  933. shader->setEntryPoint(entryPointName);
  934. if (sourceEntryPointName) {
  935. if (entryPointName == nullptr)
  936. printf("Warning: Changing source entry point name without setting an entry-point name.\n"
  937. "Use '-e <name>'.\n");
  938. shader->setSourceEntryPoint(sourceEntryPointName);
  939. }
  940. if (UserPreamble.isSet())
  941. shader->setPreamble(UserPreamble.get());
  942. shader->addProcesses(Processes);
  943. #ifndef GLSLANG_WEB
  944. // Set IO mapper binding shift values
  945. for (int r = 0; r < glslang::EResCount; ++r) {
  946. const glslang::TResourceType res = glslang::TResourceType(r);
  947. // Set base bindings
  948. shader->setShiftBinding(res, baseBinding[res][compUnit.stage]);
  949. // Set bindings for particular resource sets
  950. // TODO: use a range based for loop here, when available in all environments.
  951. for (auto i = baseBindingForSet[res][compUnit.stage].begin();
  952. i != baseBindingForSet[res][compUnit.stage].end(); ++i)
  953. shader->setShiftBindingForSet(res, i->second, i->first);
  954. }
  955. shader->setNoStorageFormat((Options & EOptionNoStorageFormat) != 0);
  956. shader->setResourceSetBinding(baseResourceSetBinding[compUnit.stage]);
  957. if (Options & EOptionAutoMapBindings)
  958. shader->setAutoMapBindings(true);
  959. if (Options & EOptionAutoMapLocations)
  960. shader->setAutoMapLocations(true);
  961. for (auto& uniOverride : uniformLocationOverrides) {
  962. shader->addUniformLocationOverride(uniOverride.first.c_str(),
  963. uniOverride.second);
  964. }
  965. shader->setUniformLocationBase(uniformBase);
  966. #endif
  967. shader->setNanMinMaxClamp(NaNClamp);
  968. #ifdef ENABLE_HLSL
  969. shader->setFlattenUniformArrays((Options & EOptionFlattenUniformArrays) != 0);
  970. if (Options & EOptionHlslIoMapping)
  971. shader->setHlslIoMapping(true);
  972. #endif
  973. if (Options & EOptionInvertY)
  974. shader->setInvertY(true);
  975. // Set up the environment, some subsettings take precedence over earlier
  976. // ways of setting things.
  977. if (Options & EOptionSpv) {
  978. shader->setEnvInput((Options & EOptionReadHlsl) ? glslang::EShSourceHlsl
  979. : glslang::EShSourceGlsl,
  980. compUnit.stage, Client, ClientInputSemanticsVersion);
  981. shader->setEnvClient(Client, ClientVersion);
  982. shader->setEnvTarget(TargetLanguage, TargetVersion);
  983. #ifdef ENABLE_HLSL
  984. if (targetHlslFunctionality1)
  985. shader->setEnvTargetHlslFunctionality1();
  986. #endif
  987. }
  988. shaders.push_back(shader);
  989. const int defaultVersion = Options & EOptionDefaultDesktop ? 110 : 100;
  990. DirStackFileIncluder includer;
  991. std::for_each(IncludeDirectoryList.rbegin(), IncludeDirectoryList.rend(), [&includer](const std::string& dir) {
  992. includer.pushExternalLocalDirectory(dir); });
  993. #ifndef GLSLANG_WEB
  994. if (Options & EOptionOutputPreprocessed) {
  995. std::string str;
  996. if (shader->preprocess(&Resources, defaultVersion, ENoProfile, false, false, messages, &str, includer)) {
  997. PutsIfNonEmpty(str.c_str());
  998. } else {
  999. CompileFailed = true;
  1000. }
  1001. StderrIfNonEmpty(shader->getInfoLog());
  1002. StderrIfNonEmpty(shader->getInfoDebugLog());
  1003. continue;
  1004. }
  1005. #endif
  1006. if (! shader->parse(&Resources, defaultVersion, false, messages, includer))
  1007. CompileFailed = true;
  1008. program.addShader(shader);
  1009. if (! (Options & EOptionSuppressInfolog) &&
  1010. ! (Options & EOptionMemoryLeakMode)) {
  1011. if (!beQuiet)
  1012. PutsIfNonEmpty(compUnit.fileName[0].c_str());
  1013. PutsIfNonEmpty(shader->getInfoLog());
  1014. PutsIfNonEmpty(shader->getInfoDebugLog());
  1015. }
  1016. }
  1017. //
  1018. // Program-level processing...
  1019. //
  1020. // Link
  1021. if (! (Options & EOptionOutputPreprocessed) && ! program.link(messages))
  1022. LinkFailed = true;
  1023. #ifndef GLSLANG_WEB
  1024. // Map IO
  1025. if (Options & EOptionSpv) {
  1026. if (!program.mapIO())
  1027. LinkFailed = true;
  1028. }
  1029. #endif
  1030. // Report
  1031. if (! (Options & EOptionSuppressInfolog) &&
  1032. ! (Options & EOptionMemoryLeakMode)) {
  1033. PutsIfNonEmpty(program.getInfoLog());
  1034. PutsIfNonEmpty(program.getInfoDebugLog());
  1035. }
  1036. #ifndef GLSLANG_WEB
  1037. // Reflect
  1038. if (Options & EOptionDumpReflection) {
  1039. program.buildReflection(ReflectOptions);
  1040. program.dumpReflection();
  1041. }
  1042. #endif
  1043. // Dump SPIR-V
  1044. if (Options & EOptionSpv) {
  1045. if (CompileFailed || LinkFailed)
  1046. printf("SPIR-V is not generated for failed compile or link\n");
  1047. else {
  1048. for (int stage = 0; stage < EShLangCount; ++stage) {
  1049. if (program.getIntermediate((EShLanguage)stage)) {
  1050. std::vector<unsigned int> spirv;
  1051. spv::SpvBuildLogger logger;
  1052. glslang::SpvOptions spvOptions;
  1053. if (Options & EOptionDebug)
  1054. spvOptions.generateDebugInfo = true;
  1055. else if (stripDebugInfo)
  1056. spvOptions.stripDebugInfo = true;
  1057. spvOptions.disableOptimizer = (Options & EOptionOptimizeDisable) != 0;
  1058. spvOptions.optimizeSize = (Options & EOptionOptimizeSize) != 0;
  1059. spvOptions.disassemble = SpvToolsDisassembler;
  1060. spvOptions.validate = SpvToolsValidate;
  1061. glslang::GlslangToSpv(*program.getIntermediate((EShLanguage)stage), spirv, &logger, &spvOptions);
  1062. // Dump the spv to a file or stdout, etc., but only if not doing
  1063. // memory/perf testing, as it's not internal to programmatic use.
  1064. if (! (Options & EOptionMemoryLeakMode)) {
  1065. printf("%s", logger.getAllMessages().c_str());
  1066. if (Options & EOptionOutputHexadecimal) {
  1067. glslang::OutputSpvHex(spirv, GetBinaryName((EShLanguage)stage), variableName);
  1068. } else {
  1069. glslang::OutputSpvBin(spirv, GetBinaryName((EShLanguage)stage));
  1070. }
  1071. #ifndef GLSLANG_WEB
  1072. if (!SpvToolsDisassembler && (Options & EOptionHumanReadableSpv))
  1073. spv::Disassemble(std::cout, spirv);
  1074. #endif
  1075. }
  1076. }
  1077. }
  1078. }
  1079. }
  1080. // Free everything up, program has to go before the shaders
  1081. // because it might have merged stuff from the shaders, and
  1082. // the stuff from the shaders has to have its destructors called
  1083. // before the pools holding the memory in the shaders is freed.
  1084. delete &program;
  1085. while (shaders.size() > 0) {
  1086. delete shaders.back();
  1087. shaders.pop_back();
  1088. }
  1089. }
  1090. //
  1091. // Do file IO part of compile and link, handing off the pure
  1092. // API/programmatic mode to CompileAndLinkShaderUnits(), which can
  1093. // be put in a loop for testing memory footprint and performance.
  1094. //
  1095. // This is just for linking mode: meaning all the shaders will be put into the
  1096. // the same program linked together.
  1097. //
  1098. // This means there are a limited number of work items (not multi-threading mode)
  1099. // and that the point is testing at the linking level. Hence, to enable
  1100. // performance and memory testing, the actual compile/link can be put in
  1101. // a loop, independent of processing the work items and file IO.
  1102. //
  1103. void CompileAndLinkShaderFiles(glslang::TWorklist& Worklist)
  1104. {
  1105. std::vector<ShaderCompUnit> compUnits;
  1106. // If this is using stdin, we can't really detect multiple different file
  1107. // units by input type. We need to assume that we're just being given one
  1108. // file of a certain type.
  1109. if ((Options & EOptionStdin) != 0) {
  1110. ShaderCompUnit compUnit(FindLanguage("stdin"));
  1111. std::istreambuf_iterator<char> begin(std::cin), end;
  1112. std::string tempString(begin, end);
  1113. char* fileText = strdup(tempString.c_str());
  1114. std::string fileName = "stdin";
  1115. compUnit.addString(fileName, fileText);
  1116. compUnits.push_back(compUnit);
  1117. } else {
  1118. // Transfer all the work items from to a simple list of
  1119. // of compilation units. (We don't care about the thread
  1120. // work-item distribution properties in this path, which
  1121. // is okay due to the limited number of shaders, know since
  1122. // they are all getting linked together.)
  1123. glslang::TWorkItem* workItem;
  1124. while (Worklist.remove(workItem)) {
  1125. ShaderCompUnit compUnit(FindLanguage(workItem->name));
  1126. char* fileText = ReadFileData(workItem->name.c_str());
  1127. if (fileText == nullptr)
  1128. usage();
  1129. compUnit.addString(workItem->name, fileText);
  1130. compUnits.push_back(compUnit);
  1131. }
  1132. }
  1133. // Actual call to programmatic processing of compile and link,
  1134. // in a loop for testing memory and performance. This part contains
  1135. // all the perf/memory that a programmatic consumer will care about.
  1136. for (int i = 0; i < ((Options & EOptionMemoryLeakMode) ? 100 : 1); ++i) {
  1137. for (int j = 0; j < ((Options & EOptionMemoryLeakMode) ? 100 : 1); ++j)
  1138. CompileAndLinkShaderUnits(compUnits);
  1139. if (Options & EOptionMemoryLeakMode)
  1140. glslang::OS_DumpMemoryCounters();
  1141. }
  1142. // free memory from ReadFileData, which got stored in a const char*
  1143. // as the first string above
  1144. for (auto it = compUnits.begin(); it != compUnits.end(); ++it)
  1145. FreeFileData(const_cast<char*>(it->text[0]));
  1146. }
  1147. int singleMain()
  1148. {
  1149. glslang::TWorklist workList;
  1150. std::for_each(WorkItems.begin(), WorkItems.end(), [&workList](std::unique_ptr<glslang::TWorkItem>& item) {
  1151. assert(item);
  1152. workList.add(item.get());
  1153. });
  1154. #ifndef GLSLANG_WEB
  1155. if (Options & EOptionDumpConfig) {
  1156. printf("%s", glslang::GetDefaultTBuiltInResourceString().c_str());
  1157. if (workList.empty())
  1158. return ESuccess;
  1159. }
  1160. #endif
  1161. if (Options & EOptionDumpBareVersion) {
  1162. printf("%d:%d.%d.%d%s\n", glslang::GetSpirvGeneratorVersion(), GLSLANG_VERSION_MAJOR, GLSLANG_VERSION_MINOR,
  1163. GLSLANG_VERSION_PATCH, GLSLANG_VERSION_FLAVOR);
  1164. if (workList.empty())
  1165. return ESuccess;
  1166. } else if (Options & EOptionDumpVersions) {
  1167. printf("Glslang Version: %d:%d.%d.%d%s\n", glslang::GetSpirvGeneratorVersion(), GLSLANG_VERSION_MAJOR,
  1168. GLSLANG_VERSION_MINOR, GLSLANG_VERSION_PATCH, GLSLANG_VERSION_FLAVOR);
  1169. printf("ESSL Version: %s\n", glslang::GetEsslVersionString());
  1170. printf("GLSL Version: %s\n", glslang::GetGlslVersionString());
  1171. std::string spirvVersion;
  1172. glslang::GetSpirvVersion(spirvVersion);
  1173. printf("SPIR-V Version %s\n", spirvVersion.c_str());
  1174. printf("GLSL.std.450 Version %d, Revision %d\n", GLSLstd450Version, GLSLstd450Revision);
  1175. printf("Khronos Tool ID %d\n", glslang::GetKhronosToolId());
  1176. printf("SPIR-V Generator Version %d\n", glslang::GetSpirvGeneratorVersion());
  1177. printf("GL_KHR_vulkan_glsl version %d\n", 100);
  1178. printf("ARB_GL_gl_spirv version %d\n", 100);
  1179. if (workList.empty())
  1180. return ESuccess;
  1181. }
  1182. if (workList.empty() && ((Options & EOptionStdin) == 0)) {
  1183. usage();
  1184. }
  1185. if (Options & EOptionStdin) {
  1186. WorkItems.push_back(std::unique_ptr<glslang::TWorkItem>{new glslang::TWorkItem("stdin")});
  1187. workList.add(WorkItems.back().get());
  1188. }
  1189. ProcessConfigFile();
  1190. if ((Options & EOptionReadHlsl) && !((Options & EOptionOutputPreprocessed) || (Options & EOptionSpv)))
  1191. Error("HLSL requires SPIR-V code generation (or preprocessing only)");
  1192. //
  1193. // Two modes:
  1194. // 1) linking all arguments together, single-threaded, new C++ interface
  1195. // 2) independent arguments, can be tackled by multiple asynchronous threads, for testing thread safety, using the old handle interface
  1196. //
  1197. if (Options & (EOptionLinkProgram | EOptionOutputPreprocessed)) {
  1198. glslang::InitializeProcess();
  1199. glslang::InitializeProcess(); // also test reference counting of users
  1200. glslang::InitializeProcess(); // also test reference counting of users
  1201. glslang::FinalizeProcess(); // also test reference counting of users
  1202. glslang::FinalizeProcess(); // also test reference counting of users
  1203. CompileAndLinkShaderFiles(workList);
  1204. glslang::FinalizeProcess();
  1205. } else {
  1206. ShInitialize();
  1207. ShInitialize(); // also test reference counting of users
  1208. ShFinalize(); // also test reference counting of users
  1209. bool printShaderNames = workList.size() > 1;
  1210. if (Options & EOptionMultiThreaded) {
  1211. std::array<std::thread, 16> threads;
  1212. for (unsigned int t = 0; t < threads.size(); ++t) {
  1213. threads[t] = std::thread(CompileShaders, std::ref(workList));
  1214. if (threads[t].get_id() == std::thread::id()) {
  1215. fprintf(stderr, "Failed to create thread\n");
  1216. return EFailThreadCreate;
  1217. }
  1218. }
  1219. std::for_each(threads.begin(), threads.end(), [](std::thread& t) { t.join(); });
  1220. } else
  1221. CompileShaders(workList);
  1222. // Print out all the resulting infologs
  1223. for (size_t w = 0; w < WorkItems.size(); ++w) {
  1224. if (WorkItems[w]) {
  1225. if (printShaderNames || WorkItems[w]->results.size() > 0)
  1226. PutsIfNonEmpty(WorkItems[w]->name.c_str());
  1227. PutsIfNonEmpty(WorkItems[w]->results.c_str());
  1228. }
  1229. }
  1230. ShFinalize();
  1231. }
  1232. if (CompileFailed)
  1233. return EFailCompile;
  1234. if (LinkFailed)
  1235. return EFailLink;
  1236. return 0;
  1237. }
  1238. int C_DECL main(int argc, char* argv[])
  1239. {
  1240. ProcessArguments(WorkItems, argc, argv);
  1241. int ret = 0;
  1242. // Loop over the entire init/finalize cycle to watch memory changes
  1243. const int iterations = 1;
  1244. if (iterations > 1)
  1245. glslang::OS_DumpMemoryCounters();
  1246. for (int i = 0; i < iterations; ++i) {
  1247. ret = singleMain();
  1248. if (iterations > 1)
  1249. glslang::OS_DumpMemoryCounters();
  1250. }
  1251. return ret;
  1252. }
  1253. //
  1254. // Deduce the language from the filename. Files must end in one of the
  1255. // following extensions:
  1256. //
  1257. // .vert = vertex
  1258. // .tesc = tessellation control
  1259. // .tese = tessellation evaluation
  1260. // .geom = geometry
  1261. // .frag = fragment
  1262. // .comp = compute
  1263. // .rgen = ray generation
  1264. // .rint = ray intersection
  1265. // .rahit = ray any hit
  1266. // .rchit = ray closest hit
  1267. // .rmiss = ray miss
  1268. // .rcall = ray callable
  1269. // .mesh = mesh
  1270. // .task = task
  1271. // Additionally, the file names may end in .<stage>.glsl and .<stage>.hlsl
  1272. // where <stage> is one of the stages listed above.
  1273. //
  1274. EShLanguage FindLanguage(const std::string& name, bool parseStageName)
  1275. {
  1276. std::string stageName;
  1277. if (shaderStageName)
  1278. stageName = shaderStageName;
  1279. else if (parseStageName) {
  1280. // Note: "first" extension means "first from the end", i.e.
  1281. // if the file is named foo.vert.glsl, then "glsl" is first,
  1282. // "vert" is second.
  1283. size_t firstExtStart = name.find_last_of(".");
  1284. bool hasFirstExt = firstExtStart != std::string::npos;
  1285. size_t secondExtStart = hasFirstExt ? name.find_last_of(".", firstExtStart - 1) : std::string::npos;
  1286. bool hasSecondExt = secondExtStart != std::string::npos;
  1287. std::string firstExt = name.substr(firstExtStart + 1, std::string::npos);
  1288. bool usesUnifiedExt = hasFirstExt && (firstExt == "glsl" || firstExt == "hlsl");
  1289. if (usesUnifiedExt && firstExt == "hlsl")
  1290. Options |= EOptionReadHlsl;
  1291. if (hasFirstExt && !usesUnifiedExt)
  1292. stageName = firstExt;
  1293. else if (usesUnifiedExt && hasSecondExt)
  1294. stageName = name.substr(secondExtStart + 1, firstExtStart - secondExtStart - 1);
  1295. else {
  1296. usage();
  1297. return EShLangVertex;
  1298. }
  1299. } else
  1300. stageName = name;
  1301. if (stageName == "vert")
  1302. return EShLangVertex;
  1303. else if (stageName == "tesc")
  1304. return EShLangTessControl;
  1305. else if (stageName == "tese")
  1306. return EShLangTessEvaluation;
  1307. else if (stageName == "geom")
  1308. return EShLangGeometry;
  1309. else if (stageName == "frag")
  1310. return EShLangFragment;
  1311. else if (stageName == "comp")
  1312. return EShLangCompute;
  1313. else if (stageName == "rgen")
  1314. return EShLangRayGen;
  1315. else if (stageName == "rint")
  1316. return EShLangIntersect;
  1317. else if (stageName == "rahit")
  1318. return EShLangAnyHit;
  1319. else if (stageName == "rchit")
  1320. return EShLangClosestHit;
  1321. else if (stageName == "rmiss")
  1322. return EShLangMiss;
  1323. else if (stageName == "rcall")
  1324. return EShLangCallable;
  1325. else if (stageName == "mesh")
  1326. return EShLangMeshNV;
  1327. else if (stageName == "task")
  1328. return EShLangTaskNV;
  1329. usage();
  1330. return EShLangVertex;
  1331. }
  1332. //
  1333. // Read a file's data into a string, and compile it using the old interface ShCompile,
  1334. // for non-linkable results.
  1335. //
  1336. void CompileFile(const char* fileName, ShHandle compiler)
  1337. {
  1338. int ret = 0;
  1339. char* shaderString;
  1340. if ((Options & EOptionStdin) != 0) {
  1341. std::istreambuf_iterator<char> begin(std::cin), end;
  1342. std::string tempString(begin, end);
  1343. shaderString = strdup(tempString.c_str());
  1344. } else {
  1345. shaderString = ReadFileData(fileName);
  1346. }
  1347. // move to length-based strings, rather than null-terminated strings
  1348. int* lengths = new int[1];
  1349. lengths[0] = (int)strlen(shaderString);
  1350. EShMessages messages = EShMsgDefault;
  1351. SetMessageOptions(messages);
  1352. if (UserPreamble.isSet())
  1353. Error("-D and -U options require -l (linking)\n");
  1354. for (int i = 0; i < ((Options & EOptionMemoryLeakMode) ? 100 : 1); ++i) {
  1355. for (int j = 0; j < ((Options & EOptionMemoryLeakMode) ? 100 : 1); ++j) {
  1356. // ret = ShCompile(compiler, shaderStrings, NumShaderStrings, lengths, EShOptNone, &Resources, Options, (Options & EOptionDefaultDesktop) ? 110 : 100, false, messages);
  1357. ret = ShCompile(compiler, &shaderString, 1, nullptr, EShOptNone, &Resources, Options, (Options & EOptionDefaultDesktop) ? 110 : 100, false, messages);
  1358. // const char* multi[12] = { "# ve", "rsion", " 300 e", "s", "\n#err",
  1359. // "or should be l", "ine 1", "string 5\n", "float glo", "bal",
  1360. // ";\n#error should be line 2\n void main() {", "global = 2.3;}" };
  1361. // const char* multi[7] = { "/", "/", "\\", "\n", "\n", "#", "version 300 es" };
  1362. // ret = ShCompile(compiler, multi, 7, nullptr, EShOptNone, &Resources, Options, (Options & EOptionDefaultDesktop) ? 110 : 100, false, messages);
  1363. }
  1364. if (Options & EOptionMemoryLeakMode)
  1365. glslang::OS_DumpMemoryCounters();
  1366. }
  1367. delete [] lengths;
  1368. FreeFileData(shaderString);
  1369. if (ret == 0)
  1370. CompileFailed = true;
  1371. }
  1372. //
  1373. // print usage to stdout
  1374. //
  1375. void usage()
  1376. {
  1377. printf("Usage: glslangValidator [option]... [file]...\n"
  1378. "\n"
  1379. "'file' can end in .<stage> for auto-stage classification, where <stage> is:\n"
  1380. " .conf to provide a config file that replaces the default configuration\n"
  1381. " (see -c option below for generating a template)\n"
  1382. " .vert for a vertex shader\n"
  1383. " .tesc for a tessellation control shader\n"
  1384. " .tese for a tessellation evaluation shader\n"
  1385. " .geom for a geometry shader\n"
  1386. " .frag for a fragment shader\n"
  1387. " .comp for a compute shader\n"
  1388. " .mesh for a mesh shader\n"
  1389. " .task for a task shader\n"
  1390. " .rgen for a ray generation shader\n"
  1391. " .rint for a ray intersection shader\n"
  1392. " .rahit for a ray any hit shader\n"
  1393. " .rchit for a ray closest hit shader\n"
  1394. " .rmiss for a ray miss shader\n"
  1395. " .rcall for a ray callable shader\n"
  1396. " .glsl for .vert.glsl, .tesc.glsl, ..., .comp.glsl compound suffixes\n"
  1397. " .hlsl for .vert.hlsl, .tesc.hlsl, ..., .comp.hlsl compound suffixes\n"
  1398. "\n"
  1399. "Options:\n"
  1400. " -C cascading errors; risk crash from accumulation of error recoveries\n"
  1401. " -D input is HLSL (this is the default when any suffix is .hlsl)\n"
  1402. " -D<name[=def]> | --define-macro <name[=def]> | --D <name[=def]>\n"
  1403. " define a pre-processor macro\n"
  1404. " -E print pre-processed GLSL; cannot be used with -l;\n"
  1405. " errors will appear on stderr\n"
  1406. " -G[ver] create SPIR-V binary, under OpenGL semantics; turns on -l;\n"
  1407. " default file name is <stage>.spv (-o overrides this);\n"
  1408. " 'ver', when present, is the version of the input semantics,\n"
  1409. " which will appear in #define GL_SPIRV ver;\n"
  1410. " '--client opengl100' is the same as -G100;\n"
  1411. " a '--target-env' for OpenGL will also imply '-G'\n"
  1412. " -H print human readable form of SPIR-V; turns on -V\n"
  1413. " -I<dir> add dir to the include search path; includer's directory\n"
  1414. " is searched first, followed by left-to-right order of -I\n"
  1415. " -Od disables optimization; may cause illegal SPIR-V for HLSL\n"
  1416. " -Os optimizes SPIR-V to minimize size\n"
  1417. " -S <stage> uses specified stage rather than parsing the file extension\n"
  1418. " choices for <stage> are vert, tesc, tese, geom, frag, or comp\n"
  1419. " -U<name> | --undef-macro <name> | --U <name>\n"
  1420. " undefine a pre-processor macro\n"
  1421. " -V[ver] create SPIR-V binary, under Vulkan semantics; turns on -l;\n"
  1422. " default file name is <stage>.spv (-o overrides this)\n"
  1423. " 'ver', when present, is the version of the input semantics,\n"
  1424. " which will appear in #define VULKAN ver\n"
  1425. " '--client vulkan100' is the same as -V100\n"
  1426. " a '--target-env' for Vulkan will also imply '-V'\n"
  1427. " -c configuration dump;\n"
  1428. " creates the default configuration file (redirect to a .conf file)\n"
  1429. " -d default to desktop (#version 110) when there is no shader #version\n"
  1430. " (default is ES version 100)\n"
  1431. " -e <name> | --entry-point <name>\n"
  1432. " specify <name> as the entry-point function name\n"
  1433. " -f{hlsl_functionality1}\n"
  1434. " 'hlsl_functionality1' enables use of the\n"
  1435. " SPV_GOOGLE_hlsl_functionality1 extension\n"
  1436. " -g generate debug information\n"
  1437. " -g0 strip debug information\n"
  1438. " -h print this usage message\n"
  1439. " -i intermediate tree (glslang AST) is printed out\n"
  1440. " -l link all input files together to form a single module\n"
  1441. " -m memory leak mode\n"
  1442. " -o <file> save binary to <file>, requires a binary option (e.g., -V)\n"
  1443. " -q dump reflection query database; requires -l for linking\n"
  1444. " -r | --relaxed-errors"
  1445. " relaxed GLSL semantic error-checking mode\n"
  1446. " -s silence syntax and semantic error reporting\n"
  1447. " -t multi-threaded mode\n"
  1448. " -v | --version\n"
  1449. " print version strings\n"
  1450. " -w | --suppress-warnings\n"
  1451. " suppress GLSL warnings, except as required by \"#extension : warn\"\n"
  1452. " -x save binary output as text-based 32-bit hexadecimal numbers\n"
  1453. " -u<name>:<loc> specify a uniform location override for --aml\n"
  1454. " --uniform-base <base> set a base to use for generated uniform locations\n"
  1455. " --auto-map-bindings | --amb automatically bind uniform variables\n"
  1456. " without explicit bindings\n"
  1457. " --auto-map-locations | --aml automatically locate input/output lacking\n"
  1458. " 'location' (fragile, not cross stage)\n"
  1459. " --client {vulkan<ver>|opengl<ver>} see -V and -G\n"
  1460. " --dump-builtin-symbols prints builtin symbol table prior each compile\n"
  1461. " -dumpfullversion | -dumpversion print bare major.minor.patchlevel\n"
  1462. " --flatten-uniform-arrays | --fua flatten uniform texture/sampler arrays to\n"
  1463. " scalars\n"
  1464. " --hlsl-offsets allow block offsets to follow HLSL rules\n"
  1465. " works independently of source language\n"
  1466. " --hlsl-iomap perform IO mapping in HLSL register space\n"
  1467. " --hlsl-enable-16bit-types allow 16-bit types in SPIR-V for HLSL\n"
  1468. " --hlsl-dx9-compatible interprets sampler declarations as a\n"
  1469. " texture/sampler combo like DirectX9 would,\n"
  1470. " and recognizes DirectX9-specific semantics\n"
  1471. " --invert-y | --iy invert position.Y output in vertex shader\n"
  1472. " --keep-uncalled | --ku don't eliminate uncalled functions\n"
  1473. " --nan-clamp favor non-NaN operand in min, max, and clamp\n"
  1474. " --no-storage-format | --nsf use Unknown image format\n"
  1475. " --quiet do not print anything to stdout, unless\n"
  1476. " requested by another option\n"
  1477. " --reflect-strict-array-suffix use strict array suffix rules when\n"
  1478. " reflecting\n"
  1479. " --reflect-basic-array-suffix arrays of basic types will have trailing [0]\n"
  1480. " --reflect-intermediate-io reflection includes inputs/outputs of linked\n"
  1481. " shaders rather than just vertex/fragment\n"
  1482. " --reflect-separate-buffers reflect buffer variables and blocks\n"
  1483. " separately to uniforms\n"
  1484. " --reflect-all-block-variables reflect all variables in blocks, whether\n"
  1485. " inactive or active\n"
  1486. " --reflect-unwrap-io-blocks unwrap input/output blocks the same as\n"
  1487. " uniform blocks\n"
  1488. " --resource-set-binding [stage] name set binding\n"
  1489. " set descriptor set and binding for\n"
  1490. " individual resources\n"
  1491. " --resource-set-binding [stage] set\n"
  1492. " set descriptor set for all resources\n"
  1493. " --rsb synonym for --resource-set-binding\n"
  1494. " --shift-image-binding [stage] num\n"
  1495. " base binding number for images (uav)\n"
  1496. " --shift-image-binding [stage] [num set]...\n"
  1497. " per-descriptor-set shift values\n"
  1498. " --sib synonym for --shift-image-binding\n"
  1499. " --shift-sampler-binding [stage] num\n"
  1500. " base binding number for samplers\n"
  1501. " --shift-sampler-binding [stage] [num set]...\n"
  1502. " per-descriptor-set shift values\n"
  1503. " --ssb synonym for --shift-sampler-binding\n"
  1504. " --shift-ssbo-binding [stage] num base binding number for SSBOs\n"
  1505. " --shift-ssbo-binding [stage] [num set]...\n"
  1506. " per-descriptor-set shift values\n"
  1507. " --sbb synonym for --shift-ssbo-binding\n"
  1508. " --shift-texture-binding [stage] num\n"
  1509. " base binding number for textures\n"
  1510. " --shift-texture-binding [stage] [num set]...\n"
  1511. " per-descriptor-set shift values\n"
  1512. " --stb synonym for --shift-texture-binding\n"
  1513. " --shift-uav-binding [stage] num base binding number for UAVs\n"
  1514. " --shift-uav-binding [stage] [num set]...\n"
  1515. " per-descriptor-set shift values\n"
  1516. " --suavb synonym for --shift-uav-binding\n"
  1517. " --shift-UBO-binding [stage] num base binding number for UBOs\n"
  1518. " --shift-UBO-binding [stage] [num set]...\n"
  1519. " per-descriptor-set shift values\n"
  1520. " --sub synonym for --shift-UBO-binding\n"
  1521. " --shift-cbuffer-binding | --scb synonyms for --shift-UBO-binding\n"
  1522. " --spirv-dis output standard-form disassembly; works only\n"
  1523. " when a SPIR-V generation option is also used\n"
  1524. " --spirv-val execute the SPIRV-Tools validator\n"
  1525. " --source-entrypoint <name> the given shader source function is\n"
  1526. " renamed to be the <name> given in -e\n"
  1527. " --sep synonym for --source-entrypoint\n"
  1528. " --stdin read from stdin instead of from a file;\n"
  1529. " requires providing the shader stage using -S\n"
  1530. " --target-env {vulkan1.0 | vulkan1.1 | vulkan1.2 | opengl | \n"
  1531. " spirv1.0 | spirv1.1 | spirv1.2 | spirv1.3 | spirv1.4 | spirv1.5}\n"
  1532. " Set the execution environment that the\n"
  1533. " generated code will be executed in.\n"
  1534. " Defaults to:\n"
  1535. " * vulkan1.0 under --client vulkan<ver>\n"
  1536. " * opengl under --client opengl<ver>\n"
  1537. " * spirv1.0 under --target-env vulkan1.0\n"
  1538. " * spirv1.3 under --target-env vulkan1.1\n"
  1539. " * spirv1.5 under --target-env vulkan1.2\n"
  1540. " Multiple --target-env can be specified.\n"
  1541. " --variable-name <name>\n"
  1542. " --vn <name> creates a C header file that contains a\n"
  1543. " uint32_t array named <name>\n"
  1544. " initialized with the shader binary code\n"
  1545. );
  1546. exit(EFailUsage);
  1547. }
  1548. #if !defined _MSC_VER && !defined MINGW_HAS_SECURE_API
  1549. #include <errno.h>
  1550. int fopen_s(
  1551. FILE** pFile,
  1552. const char* filename,
  1553. const char* mode
  1554. )
  1555. {
  1556. if (!pFile || !filename || !mode) {
  1557. return EINVAL;
  1558. }
  1559. FILE* f = fopen(filename, mode);
  1560. if (! f) {
  1561. if (errno != 0) {
  1562. return errno;
  1563. } else {
  1564. return ENOENT;
  1565. }
  1566. }
  1567. *pFile = f;
  1568. return 0;
  1569. }
  1570. #endif
  1571. //
  1572. // Malloc a string of sufficient size and read a string into it.
  1573. //
  1574. char* ReadFileData(const char* fileName)
  1575. {
  1576. FILE *in = nullptr;
  1577. int errorCode = fopen_s(&in, fileName, "r");
  1578. if (errorCode || in == nullptr)
  1579. Error("unable to open input file");
  1580. int count = 0;
  1581. while (fgetc(in) != EOF)
  1582. count++;
  1583. fseek(in, 0, SEEK_SET);
  1584. char* return_data = (char*)malloc(count + 1); // freed in FreeFileData()
  1585. if ((int)fread(return_data, 1, count, in) != count) {
  1586. free(return_data);
  1587. Error("can't read input file");
  1588. }
  1589. return_data[count] = '\0';
  1590. fclose(in);
  1591. return return_data;
  1592. }
  1593. void FreeFileData(char* data)
  1594. {
  1595. free(data);
  1596. }
  1597. void InfoLogMsg(const char* msg, const char* name, const int num)
  1598. {
  1599. if (num >= 0 )
  1600. printf("#### %s %s %d INFO LOG ####\n", msg, name, num);
  1601. else
  1602. printf("#### %s %s INFO LOG ####\n", msg, name);
  1603. }