StandAlone.cpp 94 KB

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