StandAlone.cpp 92 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256
  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, 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\n"
  1767. " (see -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]> | --define-macro <name[=def]> | --D <name[=def]>\n"
  1773. " define a pre-processor macro\n"
  1774. " -E print pre-processed GLSL; cannot be used with -l;\n"
  1775. " errors will appear on stderr\n"
  1776. " -G[ver] create SPIR-V binary, under OpenGL semantics; turns on -l;\n"
  1777. " default file name is <stage>.spv (-o overrides this);\n"
  1778. " 'ver', when present, is the version of the input semantics,\n"
  1779. " which will appear in #define GL_SPIRV ver;\n"
  1780. " '--client opengl100' is the same as -G100;\n"
  1781. " a '--target-env' for OpenGL will also imply '-G';\n"
  1782. " currently only supports GLSL\n"
  1783. " -H print human readable form of SPIR-V; turns on -V\n"
  1784. " -I<dir> add dir to the include search path; includer's directory\n"
  1785. " is searched first, followed by left-to-right order of -I\n"
  1786. " -Od disables optimization; may cause illegal SPIR-V for HLSL\n"
  1787. " -Os optimizes SPIR-V to minimize size\n"
  1788. " -P<text> | --preamble-text <text> | --P <text>\n"
  1789. " inject custom preamble text, which is treated as if it\n"
  1790. " appeared immediately after the version declaration (if any).\n"
  1791. " -R use relaxed verification rules for generating Vulkan SPIR-V,\n"
  1792. " allowing the use of default uniforms, atomic_uints, and\n"
  1793. " gl_VertexID and gl_InstanceID keywords.\n"
  1794. " -S <stage> uses specified stage rather than parsing the file extension\n"
  1795. " choices for <stage> include vert, tesc, tese, geom, frag, comp.\n"
  1796. " A full list of options is given above."
  1797. " -U<name> | --undef-macro <name> | --U <name>\n"
  1798. " undefine a pre-processor macro\n"
  1799. " -V[ver] create SPIR-V binary, under Vulkan semantics; turns on -l;\n"
  1800. " default file name is <stage>.spv (-o overrides this)\n"
  1801. " 'ver', when present, is the version of the input semantics,\n"
  1802. " which will appear in #define VULKAN ver\n"
  1803. " '--client vulkan100' is the same as -V100\n"
  1804. " a '--target-env' for Vulkan will also imply '-V'\n"
  1805. " -c configuration dump;\n"
  1806. " creates the default configuration file (redirect to a .conf file)\n"
  1807. " -d default to desktop (#version 110) when there is no shader #version\n"
  1808. " (default is ES version 100)\n"
  1809. " -e <name> | --entry-point <name>\n"
  1810. " specify <name> as the entry-point function name\n"
  1811. " -f{hlsl_functionality1}\n"
  1812. " 'hlsl_functionality1' enables use of the\n"
  1813. " SPV_GOOGLE_hlsl_functionality1 extension\n"
  1814. " -g generate debug information\n"
  1815. " -g0 strip debug information\n"
  1816. " -gV generate nonsemantic shader debug information\n"
  1817. " -gVS generate nonsemantic shader debug information with source\n"
  1818. " -h print this usage message\n"
  1819. " -i intermediate tree (glslang AST) is printed out\n"
  1820. " -l link all input files together to form a single module\n"
  1821. " -m memory leak mode\n"
  1822. " -o <file> save binary to <file>, requires a binary option (e.g., -V)\n"
  1823. " -q dump reflection query database; requires -l for linking\n"
  1824. " -r | --relaxed-errors\n"
  1825. " relaxed GLSL semantic error-checking mode\n"
  1826. " -s silence syntax and semantic error reporting\n"
  1827. " -t multi-threaded mode\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. " -u<name>:<loc> specify a uniform location override for --aml\n"
  1834. " --uniform-base <base> set a base to use for generated uniform locations\n"
  1835. " --auto-map-bindings | --amb automatically bind uniform variables\n"
  1836. " without explicit bindings\n"
  1837. " --auto-map-locations | --aml automatically locate input/output lacking\n"
  1838. " 'location' (fragile, not cross stage)\n"
  1839. " --absolute-path Prints absolute path for messages\n"
  1840. " --auto-sampled-textures Removes sampler variables and converts\n"
  1841. " existing textures to sampled textures\n"
  1842. " --client {vulkan<ver>|opengl<ver>} see -V and -G\n"
  1843. " --depfile <file> writes depfile for build systems\n"
  1844. " --dump-builtin-symbols prints builtin symbol table prior each compile\n"
  1845. " -dumpfullversion | -dumpversion print bare major.minor.patchlevel\n"
  1846. " --flatten-uniform-arrays | --fua flatten uniform texture/sampler arrays to\n"
  1847. " scalars\n"
  1848. " --glsl-version {100 | 110 | 120 | 130 | 140 | 150 |\n"
  1849. " 300es | 310es | 320es | 330\n"
  1850. " 400 | 410 | 420 | 430 | 440 | 450 | 460}\n"
  1851. " set GLSL version, overrides #version\n"
  1852. " in shader source\n"
  1853. " --hlsl-offsets allow block offsets to follow HLSL rules\n"
  1854. " works independently of source language\n"
  1855. " --hlsl-iomap perform IO mapping in HLSL register space\n"
  1856. " --hlsl-enable-16bit-types allow 16-bit types in SPIR-V for HLSL\n"
  1857. " --hlsl-dx9-compatible interprets sampler declarations as a\n"
  1858. " texture/sampler combo like DirectX9 would,\n"
  1859. " and recognizes DirectX9-specific semantics\n"
  1860. " --hlsl-dx-position-w W component of SV_Position in HLSL fragment\n"
  1861. " shaders compatible with DirectX\n"
  1862. " --invert-y | --iy invert position.Y output in vertex shader\n"
  1863. " --enhanced-msgs print more readable error messages (GLSL only)\n"
  1864. " --error-column display the column of the error along the line\n"
  1865. " --keep-uncalled | --ku don't eliminate uncalled functions\n"
  1866. " --nan-clamp favor non-NaN operand in min, max, and clamp\n"
  1867. " --no-storage-format | --nsf use Unknown image format\n"
  1868. " --quiet do not print anything to stdout, unless\n"
  1869. " requested by another option\n"
  1870. " --reflect-strict-array-suffix use strict array suffix rules when\n"
  1871. " reflecting\n"
  1872. " --reflect-basic-array-suffix arrays of basic types will have trailing [0]\n"
  1873. " --reflect-intermediate-io reflection includes inputs/outputs of linked\n"
  1874. " shaders rather than just vertex/fragment\n"
  1875. " --reflect-separate-buffers reflect buffer variables and blocks\n"
  1876. " separately to uniforms\n"
  1877. " --reflect-all-block-variables reflect all variables in blocks, whether\n"
  1878. " inactive or active\n"
  1879. " --reflect-unwrap-io-blocks unwrap input/output blocks the same as\n"
  1880. " uniform blocks\n"
  1881. " --resource-set-binding [stage] name set binding\n"
  1882. " set descriptor set and binding for\n"
  1883. " individual resources\n"
  1884. " --resource-set-binding [stage] set\n"
  1885. " set descriptor set for all resources\n"
  1886. " --rsb synonym for --resource-set-binding\n"
  1887. " --set-block-backing name {uniform|buffer|push_constant}\n"
  1888. " changes the backing type of a uniform, buffer,\n"
  1889. " or push_constant block declared in\n"
  1890. " in the program, when using -R option.\n"
  1891. " This can be used to change the backing\n"
  1892. " for existing blocks as well as implicit ones\n"
  1893. " such as 'gl_DefaultUniformBlock'.\n"
  1894. " --sbs synonym for set-block-storage\n"
  1895. " --set-atomic-counter-block name set\n"
  1896. " set name, and descriptor set for\n"
  1897. " atomic counter blocks, with -R opt\n"
  1898. " --sacb synonym for set-atomic-counter-block\n"
  1899. " --set-default-uniform-block name set binding\n"
  1900. " set name, descriptor set, and binding for\n"
  1901. " global default-uniform-block, with -R opt\n"
  1902. " --sdub synonym for set-default-uniform-block\n"
  1903. " --shift-image-binding [stage] num\n"
  1904. " base binding number for images (uav)\n"
  1905. " --shift-image-binding [stage] [num set]...\n"
  1906. " per-descriptor-set shift values\n"
  1907. " --sib synonym for --shift-image-binding\n"
  1908. " --shift-sampler-binding [stage] num\n"
  1909. " base binding number for samplers\n"
  1910. " --shift-sampler-binding [stage] [num set]...\n"
  1911. " per-descriptor-set shift values\n"
  1912. " --ssb synonym for --shift-sampler-binding\n"
  1913. " --shift-ssbo-binding [stage] num base binding number for SSBOs\n"
  1914. " --shift-ssbo-binding [stage] [num set]...\n"
  1915. " per-descriptor-set shift values\n"
  1916. " --sbb synonym for --shift-ssbo-binding\n"
  1917. " --shift-texture-binding [stage] num\n"
  1918. " base binding number for textures\n"
  1919. " --shift-texture-binding [stage] [num set]...\n"
  1920. " per-descriptor-set shift values\n"
  1921. " --stb synonym for --shift-texture-binding\n"
  1922. " --shift-uav-binding [stage] num base binding number for UAVs\n"
  1923. " --shift-uav-binding [stage] [num set]...\n"
  1924. " per-descriptor-set shift values\n"
  1925. " --suavb synonym for --shift-uav-binding\n"
  1926. " --shift-UBO-binding [stage] num base binding number for UBOs\n"
  1927. " --shift-UBO-binding [stage] [num set]...\n"
  1928. " per-descriptor-set shift values\n"
  1929. " --sub synonym for --shift-UBO-binding\n"
  1930. " --shift-cbuffer-binding | --scb synonyms for --shift-UBO-binding\n"
  1931. " --spirv-dis output standard-form disassembly; works only\n"
  1932. " when a SPIR-V generation option is also used\n"
  1933. " --spirv-val execute the SPIRV-Tools validator\n"
  1934. " --source-entrypoint <name> the given shader source function is\n"
  1935. " renamed to be the <name> given in -e\n"
  1936. " --sep synonym for --source-entrypoint\n"
  1937. " --stdin read from stdin instead of from a file;\n"
  1938. " requires providing the shader stage using -S\n"
  1939. " --target-env {vulkan1.0 | vulkan1.1 | vulkan1.2 | vulkan1.3 | opengl |\n"
  1940. " spirv1.0 | spirv1.1 | spirv1.2 | spirv1.3 | spirv1.4 |\n"
  1941. " spirv1.5 | spirv1.6}\n"
  1942. " Set the execution environment that the\n"
  1943. " generated code will be executed in.\n"
  1944. " Defaults to:\n"
  1945. " * vulkan1.0 under --client vulkan<ver>\n"
  1946. " * opengl under --client opengl<ver>\n"
  1947. " * spirv1.0 under --target-env vulkan1.0\n"
  1948. " * spirv1.3 under --target-env vulkan1.1\n"
  1949. " * spirv1.5 under --target-env vulkan1.2\n"
  1950. " * spirv1.6 under --target-env vulkan1.3\n"
  1951. " Multiple --target-env can be specified.\n"
  1952. " --variable-name <name>\n"
  1953. " --vn <name> creates a C header file that contains a\n"
  1954. " uint32_t array named <name>\n"
  1955. " initialized with the shader binary code\n"
  1956. " --no-link Only compile shader; do not link (GLSL-only)\n"
  1957. " NOTE: this option will set the export linkage\n"
  1958. " attribute on all functions\n"
  1959. " --lto perform link time optimization\n"
  1960. " --validate-io validate cross stage IO\n");
  1961. exit(EFailUsage);
  1962. }
  1963. #if !defined _MSC_VER && !defined MINGW_HAS_SECURE_API
  1964. #include <errno.h>
  1965. int fopen_s(
  1966. FILE** pFile,
  1967. const char* filename,
  1968. const char* mode
  1969. )
  1970. {
  1971. if (!pFile || !filename || !mode) {
  1972. return EINVAL;
  1973. }
  1974. FILE* f = fopen(filename, mode);
  1975. if (! f) {
  1976. if (errno != 0) {
  1977. return errno;
  1978. } else {
  1979. return ENOENT;
  1980. }
  1981. }
  1982. *pFile = f;
  1983. return 0;
  1984. }
  1985. #endif
  1986. //
  1987. // Malloc a string of sufficient size and read a string into it.
  1988. //
  1989. char* ReadFileData(const char* fileName)
  1990. {
  1991. FILE *in = nullptr;
  1992. int errorCode = fopen_s(&in, fileName, "r");
  1993. if (errorCode || in == nullptr)
  1994. Error("unable to open input file");
  1995. int count = 0;
  1996. while (fgetc(in) != EOF)
  1997. count++;
  1998. fseek(in, 0, SEEK_SET);
  1999. if (count > 3) {
  2000. unsigned char head[3];
  2001. if (fread(head, 1, 3, in) == 3) {
  2002. if (head[0] == 0xef && head[1] == 0xbb && head[2] == 0xbf) {
  2003. // skip BOM
  2004. count -= 3;
  2005. } else {
  2006. fseek(in, 0, SEEK_SET);
  2007. }
  2008. } else {
  2009. Error("can't read input file");
  2010. }
  2011. }
  2012. char* return_data = (char*)malloc(count + 1); // freed in FreeFileData()
  2013. if ((int)fread(return_data, 1, count, in) != count) {
  2014. free(return_data);
  2015. Error("can't read input file");
  2016. }
  2017. return_data[count] = '\0';
  2018. fclose(in);
  2019. return return_data;
  2020. }
  2021. void FreeFileData(char* data)
  2022. {
  2023. free(data);
  2024. }
  2025. void InfoLogMsg(const char* msg, const char* name, const int num)
  2026. {
  2027. if (num >= 0 )
  2028. printf("#### %s %s %d INFO LOG ####\n", msg, name, num);
  2029. else
  2030. printf("#### %s %s INFO LOG ####\n", msg, name);
  2031. }