StandAlone.cpp 95 KB

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