StandAlone.cpp 71 KB

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