StandAlone.cpp 93 KB

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