Fix variable scoping of do-while
[platform/upstream/glslang.git] / glslang / MachineIndependent / ShaderLang.cpp
1 //
2 // Copyright (C) 2002-2005  3Dlabs Inc. Ltd.
3 // Copyright (C) 2013-2016 LunarG, Inc.
4 // Copyright (C) 2015-2020 Google, Inc.
5 //
6 // All rights reserved.
7 //
8 // Redistribution and use in source and binary forms, with or without
9 // modification, are permitted provided that the following conditions
10 // are met:
11 //
12 //    Redistributions of source code must retain the above copyright
13 //    notice, this list of conditions and the following disclaimer.
14 //
15 //    Redistributions in binary form must reproduce the above
16 //    copyright notice, this list of conditions and the following
17 //    disclaimer in the documentation and/or other materials provided
18 //    with the distribution.
19 //
20 //    Neither the name of 3Dlabs Inc. Ltd. nor the names of its
21 //    contributors may be used to endorse or promote products derived
22 //    from this software without specific prior written permission.
23 //
24 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
25 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
26 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
27 // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
28 // COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
29 // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
30 // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
31 // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
32 // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
33 // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
34 // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
35 // POSSIBILITY OF SUCH DAMAGE.
36 //
37
38 //
39 // Implement the top-level of interface to the compiler/linker,
40 // as defined in ShaderLang.h
41 // This is the platform independent interface between an OGL driver
42 // and the shading language compiler/linker.
43 //
44 #include <cstring>
45 #include <iostream>
46 #include <sstream>
47 #include <memory>
48 #include "SymbolTable.h"
49 #include "ParseHelper.h"
50 #include "Scan.h"
51 #include "ScanContext.h"
52
53 #ifdef ENABLE_HLSL
54 #include "../HLSL/hlslParseHelper.h"
55 #include "../HLSL/hlslParseables.h"
56 #include "../HLSL/hlslScanContext.h"
57 #endif
58
59 #include "../Include/ShHandle.h"
60 #include "../../OGLCompilersDLL/InitializeDll.h"
61
62 #include "preprocessor/PpContext.h"
63
64 #define SH_EXPORTING
65 #include "../Public/ShaderLang.h"
66 #include "reflection.h"
67 #include "iomapper.h"
68 #include "Initialize.h"
69
70 // TODO: this really shouldn't be here, it is only because of the trial addition
71 // of printing pre-processed tokens, which requires knowing the string literal
72 // token to print ", but none of that seems appropriate for this file.
73 #include "preprocessor/PpTokens.h"
74
75 // Build-time generated includes
76 #include "glslang/build_info.h"
77
78 namespace { // anonymous namespace for file-local functions and symbols
79
80 // Total number of successful initializers of glslang: a refcount
81 // Shared global; access should be protected by a global mutex/critical section.
82 int NumberOfClients = 0;
83
84 using namespace glslang;
85
86 // Create a language specific version of parseables.
87 TBuiltInParseables* CreateBuiltInParseables(TInfoSink& infoSink, EShSource source)
88 {
89     switch (source) {
90     case EShSourceGlsl: return new TBuiltIns();              // GLSL builtIns
91 #ifdef ENABLE_HLSL
92     case EShSourceHlsl: return new TBuiltInParseablesHlsl(); // HLSL intrinsics
93 #endif
94
95     default:
96         infoSink.info.message(EPrefixInternalError, "Unable to determine source language");
97         return nullptr;
98     }
99 }
100
101 // Create a language specific version of a parse context.
102 TParseContextBase* CreateParseContext(TSymbolTable& symbolTable, TIntermediate& intermediate,
103                                       int version, EProfile profile, EShSource source,
104                                       EShLanguage language, TInfoSink& infoSink,
105                                       SpvVersion spvVersion, bool forwardCompatible, EShMessages messages,
106                                       bool parsingBuiltIns, std::string sourceEntryPointName = "")
107 {
108     switch (source) {
109     case EShSourceGlsl: {
110         if (sourceEntryPointName.size() == 0)
111             intermediate.setEntryPointName("main");
112         TString entryPoint = sourceEntryPointName.c_str();
113         return new TParseContext(symbolTable, intermediate, parsingBuiltIns, version, profile, spvVersion,
114                                  language, infoSink, forwardCompatible, messages, &entryPoint);
115     }
116 #ifdef ENABLE_HLSL
117     case EShSourceHlsl:
118         return new HlslParseContext(symbolTable, intermediate, parsingBuiltIns, version, profile, spvVersion,
119                                     language, infoSink, sourceEntryPointName.c_str(), forwardCompatible, messages);
120 #endif
121     default:
122         infoSink.info.message(EPrefixInternalError, "Unable to determine source language");
123         return nullptr;
124     }
125 }
126
127 // Local mapping functions for making arrays of symbol tables....
128
129 const int VersionCount = 17;  // index range in MapVersionToIndex
130
131 int MapVersionToIndex(int version)
132 {
133     int index = 0;
134
135     switch (version) {
136     case 100: index =  0; break;
137     case 110: index =  1; break;
138     case 120: index =  2; break;
139     case 130: index =  3; break;
140     case 140: index =  4; break;
141     case 150: index =  5; break;
142     case 300: index =  6; break;
143     case 330: index =  7; break;
144     case 400: index =  8; break;
145     case 410: index =  9; break;
146     case 420: index = 10; break;
147     case 430: index = 11; break;
148     case 440: index = 12; break;
149     case 310: index = 13; break;
150     case 450: index = 14; break;
151     case 500: index =  0; break; // HLSL
152     case 320: index = 15; break;
153     case 460: index = 16; break;
154     default:  assert(0);  break;
155     }
156
157     assert(index < VersionCount);
158
159     return index;
160 }
161
162 const int SpvVersionCount = 4;  // index range in MapSpvVersionToIndex
163
164 int MapSpvVersionToIndex(const SpvVersion& spvVersion)
165 {
166     int index = 0;
167
168     if (spvVersion.openGl > 0)
169         index = 1;
170     else if (spvVersion.vulkan > 0) {
171         if (!spvVersion.vulkanRelaxed)
172             index = 2;
173         else
174             index = 3;
175     }
176
177     assert(index < SpvVersionCount);
178
179     return index;
180 }
181
182 const int ProfileCount = 4;   // index range in MapProfileToIndex
183
184 int MapProfileToIndex(EProfile profile)
185 {
186     int index = 0;
187
188     switch (profile) {
189     case ENoProfile:            index = 0; break;
190     case ECoreProfile:          index = 1; break;
191     case ECompatibilityProfile: index = 2; break;
192     case EEsProfile:            index = 3; break;
193     default:                               break;
194     }
195
196     assert(index < ProfileCount);
197
198     return index;
199 }
200
201 const int SourceCount = 2;
202
203 int MapSourceToIndex(EShSource source)
204 {
205     int index = 0;
206
207     switch (source) {
208     case EShSourceGlsl: index = 0; break;
209     case EShSourceHlsl: index = 1; break;
210     default:                       break;
211     }
212
213     assert(index < SourceCount);
214
215     return index;
216 }
217
218 // only one of these needed for non-ES; ES needs 2 for different precision defaults of built-ins
219 enum EPrecisionClass {
220     EPcGeneral,
221     EPcFragment,
222     EPcCount
223 };
224
225 // A process-global symbol table per version per profile for built-ins common
226 // to multiple stages (languages), and a process-global symbol table per version
227 // per profile per stage for built-ins unique to each stage.  They will be sparsely
228 // populated, so they will only be generated as needed.
229 //
230 // Each has a different set of built-ins, and we want to preserve that from
231 // compile to compile.
232 //
233 TSymbolTable* CommonSymbolTable[VersionCount][SpvVersionCount][ProfileCount][SourceCount][EPcCount] = {};
234 TSymbolTable* SharedSymbolTables[VersionCount][SpvVersionCount][ProfileCount][SourceCount][EShLangCount] = {};
235
236 TPoolAllocator* PerProcessGPA = nullptr;
237
238 //
239 // Parse and add to the given symbol table the content of the given shader string.
240 //
241 bool InitializeSymbolTable(const TString& builtIns, int version, EProfile profile, const SpvVersion& spvVersion, EShLanguage language,
242                            EShSource source, TInfoSink& infoSink, TSymbolTable& symbolTable)
243 {
244     TIntermediate intermediate(language, version, profile);
245
246     intermediate.setSource(source);
247
248     std::unique_ptr<TParseContextBase> parseContext(CreateParseContext(symbolTable, intermediate, version, profile, source,
249                                                                        language, infoSink, spvVersion, true, EShMsgDefault,
250                                                                        true));
251
252     TShader::ForbidIncluder includer;
253     TPpContext ppContext(*parseContext, "", includer);
254     TScanContext scanContext(*parseContext);
255     parseContext->setScanContext(&scanContext);
256     parseContext->setPpContext(&ppContext);
257
258     //
259     // Push the symbol table to give it an initial scope.  This
260     // push should not have a corresponding pop, so that built-ins
261     // are preserved, and the test for an empty table fails.
262     //
263
264     symbolTable.push();
265
266     const char* builtInShaders[2];
267     size_t builtInLengths[2];
268     builtInShaders[0] = builtIns.c_str();
269     builtInLengths[0] = builtIns.size();
270
271     if (builtInLengths[0] == 0)
272         return true;
273
274     TInputScanner input(1, builtInShaders, builtInLengths);
275     if (! parseContext->parseShaderStrings(ppContext, input) != 0) {
276         infoSink.info.message(EPrefixInternalError, "Unable to parse built-ins");
277         printf("Unable to parse built-ins\n%s\n", infoSink.info.c_str());
278         printf("%s\n", builtInShaders[0]);
279
280         return false;
281     }
282
283     return true;
284 }
285
286 int CommonIndex(EProfile profile, EShLanguage language)
287 {
288     return (profile == EEsProfile && language == EShLangFragment) ? EPcFragment : EPcGeneral;
289 }
290
291 //
292 // To initialize per-stage shared tables, with the common table already complete.
293 //
294 void InitializeStageSymbolTable(TBuiltInParseables& builtInParseables, int version, EProfile profile, const SpvVersion& spvVersion,
295                                 EShLanguage language, EShSource source, TInfoSink& infoSink, TSymbolTable** commonTable,
296                                 TSymbolTable** symbolTables)
297 {
298 #ifdef GLSLANG_WEB
299     profile = EEsProfile;
300     version = 310;
301 #elif defined(GLSLANG_ANGLE)
302     profile = ECoreProfile;
303     version = 450;
304 #endif
305
306     (*symbolTables[language]).adoptLevels(*commonTable[CommonIndex(profile, language)]);
307     InitializeSymbolTable(builtInParseables.getStageString(language), version, profile, spvVersion, language, source,
308                           infoSink, *symbolTables[language]);
309     builtInParseables.identifyBuiltIns(version, profile, spvVersion, language, *symbolTables[language]);
310     if (profile == EEsProfile && version >= 300)
311         (*symbolTables[language]).setNoBuiltInRedeclarations();
312     if (version == 110)
313         (*symbolTables[language]).setSeparateNameSpaces();
314 }
315
316 //
317 // Initialize the full set of shareable symbol tables;
318 // The common (cross-stage) and those shareable per-stage.
319 //
320 bool InitializeSymbolTables(TInfoSink& infoSink, TSymbolTable** commonTable,  TSymbolTable** symbolTables, int version, EProfile profile, const SpvVersion& spvVersion, EShSource source)
321 {
322 #ifdef GLSLANG_WEB
323     profile = EEsProfile;
324     version = 310;
325 #elif defined(GLSLANG_ANGLE)
326     profile = ECoreProfile;
327     version = 450;
328 #endif
329
330     std::unique_ptr<TBuiltInParseables> builtInParseables(CreateBuiltInParseables(infoSink, source));
331
332     if (builtInParseables == nullptr)
333         return false;
334
335     builtInParseables->initialize(version, profile, spvVersion);
336
337     // do the common tables
338     InitializeSymbolTable(builtInParseables->getCommonString(), version, profile, spvVersion, EShLangVertex, source,
339                           infoSink, *commonTable[EPcGeneral]);
340     if (profile == EEsProfile)
341         InitializeSymbolTable(builtInParseables->getCommonString(), version, profile, spvVersion, EShLangFragment, source,
342                               infoSink, *commonTable[EPcFragment]);
343
344     // do the per-stage tables
345
346     // always have vertex and fragment
347     InitializeStageSymbolTable(*builtInParseables, version, profile, spvVersion, EShLangVertex, source,
348                                infoSink, commonTable, symbolTables);
349     InitializeStageSymbolTable(*builtInParseables, version, profile, spvVersion, EShLangFragment, source,
350                                infoSink, commonTable, symbolTables);
351
352 #ifndef GLSLANG_WEB
353     // check for tessellation
354     if ((profile != EEsProfile && version >= 150) ||
355         (profile == EEsProfile && version >= 310)) {
356         InitializeStageSymbolTable(*builtInParseables, version, profile, spvVersion, EShLangTessControl, source,
357                                    infoSink, commonTable, symbolTables);
358         InitializeStageSymbolTable(*builtInParseables, version, profile, spvVersion, EShLangTessEvaluation, source,
359                                    infoSink, commonTable, symbolTables);
360     }
361
362     // check for geometry
363     if ((profile != EEsProfile && version >= 150) ||
364         (profile == EEsProfile && version >= 310))
365         InitializeStageSymbolTable(*builtInParseables, version, profile, spvVersion, EShLangGeometry, source,
366                                    infoSink, commonTable, symbolTables);
367
368     // check for compute
369     if ((profile != EEsProfile && version >= 420) ||
370         (profile == EEsProfile && version >= 310))
371         InitializeStageSymbolTable(*builtInParseables, version, profile, spvVersion, EShLangCompute, source,
372                                    infoSink, commonTable, symbolTables);
373
374 #ifndef GLSLANG_ANGLE
375     // check for ray tracing stages
376     if (profile != EEsProfile && version >= 450) {
377         InitializeStageSymbolTable(*builtInParseables, version, profile, spvVersion, EShLangRayGen, source,
378             infoSink, commonTable, symbolTables);
379         InitializeStageSymbolTable(*builtInParseables, version, profile, spvVersion, EShLangIntersect, source,
380             infoSink, commonTable, symbolTables);
381         InitializeStageSymbolTable(*builtInParseables, version, profile, spvVersion, EShLangAnyHit, source,
382             infoSink, commonTable, symbolTables);
383         InitializeStageSymbolTable(*builtInParseables, version, profile, spvVersion, EShLangClosestHit, source,
384             infoSink, commonTable, symbolTables);
385         InitializeStageSymbolTable(*builtInParseables, version, profile, spvVersion, EShLangMiss, source,
386             infoSink, commonTable, symbolTables);
387         InitializeStageSymbolTable(*builtInParseables, version, profile, spvVersion, EShLangCallable, source,
388             infoSink, commonTable, symbolTables);
389     }
390
391     // check for mesh
392     if ((profile != EEsProfile && version >= 450) ||
393         (profile == EEsProfile && version >= 320))
394         InitializeStageSymbolTable(*builtInParseables, version, profile, spvVersion, EShLangMeshNV, source,
395                                    infoSink, commonTable, symbolTables);
396
397     // check for task
398     if ((profile != EEsProfile && version >= 450) ||
399         (profile == EEsProfile && version >= 320))
400         InitializeStageSymbolTable(*builtInParseables, version, profile, spvVersion, EShLangTaskNV, source,
401                                    infoSink, commonTable, symbolTables);
402 #endif // !GLSLANG_ANGLE
403 #endif // !GLSLANG_WEB
404
405     return true;
406 }
407
408 bool AddContextSpecificSymbols(const TBuiltInResource* resources, TInfoSink& infoSink, TSymbolTable& symbolTable, int version,
409                                EProfile profile, const SpvVersion& spvVersion, EShLanguage language, EShSource source)
410 {
411     std::unique_ptr<TBuiltInParseables> builtInParseables(CreateBuiltInParseables(infoSink, source));
412
413     if (builtInParseables == nullptr)
414         return false;
415
416     builtInParseables->initialize(*resources, version, profile, spvVersion, language);
417     InitializeSymbolTable(builtInParseables->getCommonString(), version, profile, spvVersion, language, source, infoSink, symbolTable);
418     builtInParseables->identifyBuiltIns(version, profile, spvVersion, language, symbolTable, *resources);
419
420     return true;
421 }
422
423 //
424 // To do this on the fly, we want to leave the current state of our thread's
425 // pool allocator intact, so:
426 //  - Switch to a new pool for parsing the built-ins
427 //  - Do the parsing, which builds the symbol table, using the new pool
428 //  - Switch to the process-global pool to save a copy of the resulting symbol table
429 //  - Free up the new pool used to parse the built-ins
430 //  - Switch back to the original thread's pool
431 //
432 // This only gets done the first time any thread needs a particular symbol table
433 // (lazy evaluation).
434 //
435 void SetupBuiltinSymbolTable(int version, EProfile profile, const SpvVersion& spvVersion, EShSource source)
436 {
437     TInfoSink infoSink;
438
439     // Make sure only one thread tries to do this at a time
440     glslang::GetGlobalLock();
441
442     // See if it's already been done for this version/profile combination
443     int versionIndex = MapVersionToIndex(version);
444     int spvVersionIndex = MapSpvVersionToIndex(spvVersion);
445     int profileIndex = MapProfileToIndex(profile);
446     int sourceIndex = MapSourceToIndex(source);
447     if (CommonSymbolTable[versionIndex][spvVersionIndex][profileIndex][sourceIndex][EPcGeneral]) {
448         glslang::ReleaseGlobalLock();
449
450         return;
451     }
452
453     // Switch to a new pool
454     TPoolAllocator& previousAllocator = GetThreadPoolAllocator();
455     TPoolAllocator* builtInPoolAllocator = new TPoolAllocator;
456     SetThreadPoolAllocator(builtInPoolAllocator);
457
458     // Dynamically allocate the local symbol tables so we can control when they are deallocated WRT when the pool is popped.
459     TSymbolTable* commonTable[EPcCount];
460     TSymbolTable* stageTables[EShLangCount];
461     for (int precClass = 0; precClass < EPcCount; ++precClass)
462         commonTable[precClass] = new TSymbolTable;
463     for (int stage = 0; stage < EShLangCount; ++stage)
464         stageTables[stage] = new TSymbolTable;
465
466     // Generate the local symbol tables using the new pool
467     InitializeSymbolTables(infoSink, commonTable, stageTables, version, profile, spvVersion, source);
468
469     // Switch to the process-global pool
470     SetThreadPoolAllocator(PerProcessGPA);
471
472     // Copy the local symbol tables from the new pool to the global tables using the process-global pool
473     for (int precClass = 0; precClass < EPcCount; ++precClass) {
474         if (! commonTable[precClass]->isEmpty()) {
475             CommonSymbolTable[versionIndex][spvVersionIndex][profileIndex][sourceIndex][precClass] = new TSymbolTable;
476             CommonSymbolTable[versionIndex][spvVersionIndex][profileIndex][sourceIndex][precClass]->copyTable(*commonTable[precClass]);
477             CommonSymbolTable[versionIndex][spvVersionIndex][profileIndex][sourceIndex][precClass]->readOnly();
478         }
479     }
480     for (int stage = 0; stage < EShLangCount; ++stage) {
481         if (! stageTables[stage]->isEmpty()) {
482             SharedSymbolTables[versionIndex][spvVersionIndex][profileIndex][sourceIndex][stage] = new TSymbolTable;
483             SharedSymbolTables[versionIndex][spvVersionIndex][profileIndex][sourceIndex][stage]->adoptLevels(*CommonSymbolTable
484                               [versionIndex][spvVersionIndex][profileIndex][sourceIndex][CommonIndex(profile, (EShLanguage)stage)]);
485             SharedSymbolTables[versionIndex][spvVersionIndex][profileIndex][sourceIndex][stage]->copyTable(*stageTables[stage]);
486             SharedSymbolTables[versionIndex][spvVersionIndex][profileIndex][sourceIndex][stage]->readOnly();
487         }
488     }
489
490     // Clean up the local tables before deleting the pool they used.
491     for (int precClass = 0; precClass < EPcCount; ++precClass)
492         delete commonTable[precClass];
493     for (int stage = 0; stage < EShLangCount; ++stage)
494         delete stageTables[stage];
495
496     delete builtInPoolAllocator;
497     SetThreadPoolAllocator(&previousAllocator);
498
499     glslang::ReleaseGlobalLock();
500 }
501
502 // Function to Print all builtins
503 void DumpBuiltinSymbolTable(TInfoSink& infoSink, const TSymbolTable& symbolTable)
504 {
505 #if !defined(GLSLANG_WEB) && !defined(GLSLANG_ANGLE)
506     infoSink.debug << "BuiltinSymbolTable {\n";
507
508     symbolTable.dump(infoSink, true);
509
510     infoSink.debug << "}\n";
511 #endif
512 }
513
514 // Return true if the shader was correctly specified for version/profile/stage.
515 bool DeduceVersionProfile(TInfoSink& infoSink, EShLanguage stage, bool versionNotFirst, int defaultVersion,
516                           EShSource source, int& version, EProfile& profile, const SpvVersion& spvVersion)
517 {
518     const int FirstProfileVersion = 150;
519     bool correct = true;
520
521     if (source == EShSourceHlsl) {
522         version = 500;          // shader model; currently a characteristic of glslang, not the input
523         profile = ECoreProfile; // allow doubles in prototype parsing
524         return correct;
525     }
526
527     // Get a version...
528     if (version == 0) {
529         version = defaultVersion;
530         // infoSink.info.message(EPrefixWarning, "#version: statement missing; use #version on first line of shader");
531     }
532
533     // Get a good profile...
534     if (profile == ENoProfile) {
535         if (version == 300 || version == 310 || version == 320) {
536             correct = false;
537             infoSink.info.message(EPrefixError, "#version: versions 300, 310, and 320 require specifying the 'es' profile");
538             profile = EEsProfile;
539         } else if (version == 100)
540             profile = EEsProfile;
541         else if (version >= FirstProfileVersion)
542             profile = ECoreProfile;
543         else
544             profile = ENoProfile;
545     } else {
546         // a profile was provided...
547         if (version < 150) {
548             correct = false;
549             infoSink.info.message(EPrefixError, "#version: versions before 150 do not allow a profile token");
550             if (version == 100)
551                 profile = EEsProfile;
552             else
553                 profile = ENoProfile;
554         } else if (version == 300 || version == 310 || version == 320) {
555             if (profile != EEsProfile) {
556                 correct = false;
557                 infoSink.info.message(EPrefixError, "#version: versions 300, 310, and 320 support only the es profile");
558             }
559             profile = EEsProfile;
560         } else {
561             if (profile == EEsProfile) {
562                 correct = false;
563                 infoSink.info.message(EPrefixError, "#version: only version 300, 310, and 320 support the es profile");
564                 if (version >= FirstProfileVersion)
565                     profile = ECoreProfile;
566                 else
567                     profile = ENoProfile;
568             }
569             // else: typical desktop case... e.g., "#version 410 core"
570         }
571     }
572
573     // Fix version...
574     switch (version) {
575     // ES versions
576     case 100: break;
577     case 300: break;
578     case 310: break;
579     case 320: break;
580
581     // desktop versions
582     case 110: break;
583     case 120: break;
584     case 130: break;
585     case 140: break;
586     case 150: break;
587     case 330: break;
588     case 400: break;
589     case 410: break;
590     case 420: break;
591     case 430: break;
592     case 440: break;
593     case 450: break;
594     case 460: break;
595
596     // unknown version
597     default:
598         correct = false;
599         infoSink.info.message(EPrefixError, "version not supported");
600         if (profile == EEsProfile)
601             version = 310;
602         else {
603             version = 450;
604             profile = ECoreProfile;
605         }
606         break;
607     }
608
609 #if !defined(GLSLANG_WEB) && !defined(GLSLANG_ANGLE)
610     // Correct for stage type...
611     switch (stage) {
612     case EShLangGeometry:
613         if ((profile == EEsProfile && version < 310) ||
614             (profile != EEsProfile && version < 150)) {
615             correct = false;
616             infoSink.info.message(EPrefixError, "#version: geometry shaders require es profile with version 310 or non-es profile with version 150 or above");
617             version = (profile == EEsProfile) ? 310 : 150;
618             if (profile == EEsProfile || profile == ENoProfile)
619                 profile = ECoreProfile;
620         }
621         break;
622     case EShLangTessControl:
623     case EShLangTessEvaluation:
624         if ((profile == EEsProfile && version < 310) ||
625             (profile != EEsProfile && version < 150)) {
626             correct = false;
627             infoSink.info.message(EPrefixError, "#version: tessellation shaders require es profile with version 310 or non-es profile with version 150 or above");
628             version = (profile == EEsProfile) ? 310 : 400; // 150 supports the extension, correction is to 400 which does not
629             if (profile == EEsProfile || profile == ENoProfile)
630                 profile = ECoreProfile;
631         }
632         break;
633     case EShLangCompute:
634         if ((profile == EEsProfile && version < 310) ||
635             (profile != EEsProfile && version < 420)) {
636             correct = false;
637             infoSink.info.message(EPrefixError, "#version: compute shaders require es profile with version 310 or above, or non-es profile with version 420 or above");
638             version = profile == EEsProfile ? 310 : 420;
639         }
640         break;
641     case EShLangRayGen:
642     case EShLangIntersect:
643     case EShLangAnyHit:
644     case EShLangClosestHit:
645     case EShLangMiss:
646     case EShLangCallable:
647         if (profile == EEsProfile || version < 460) {
648             correct = false;
649             infoSink.info.message(EPrefixError, "#version: ray tracing shaders require non-es profile with version 460 or above");
650             version = 460;
651         }
652         break;
653     case EShLangMeshNV:
654     case EShLangTaskNV:
655         if ((profile == EEsProfile && version < 320) ||
656             (profile != EEsProfile && version < 450)) {
657             correct = false;
658             infoSink.info.message(EPrefixError, "#version: mesh/task shaders require es profile with version 320 or above, or non-es profile with version 450 or above");
659             version = profile == EEsProfile ? 320 : 450;
660         }
661     default:
662         break;
663     }
664
665     if (profile == EEsProfile && version >= 300 && versionNotFirst) {
666         correct = false;
667         infoSink.info.message(EPrefixError, "#version: statement must appear first in es-profile shader; before comments or newlines");
668     }
669
670     // Check for SPIR-V compatibility
671     if (spvVersion.spv != 0) {
672         switch (profile) {
673         case EEsProfile:
674             if (version < 310) {
675                 correct = false;
676                 infoSink.info.message(EPrefixError, "#version: ES shaders for SPIR-V require version 310 or higher");
677                 version = 310;
678             }
679             break;
680         case ECompatibilityProfile:
681             infoSink.info.message(EPrefixError, "#version: compilation for SPIR-V does not support the compatibility profile");
682             break;
683         default:
684             if (spvVersion.vulkan > 0 && version < 140) {
685                 correct = false;
686                 infoSink.info.message(EPrefixError, "#version: Desktop shaders for Vulkan SPIR-V require version 140 or higher");
687                 version = 140;
688             }
689             if (spvVersion.openGl >= 100 && version < 330) {
690                 correct = false;
691                 infoSink.info.message(EPrefixError, "#version: Desktop shaders for OpenGL SPIR-V require version 330 or higher");
692                 version = 330;
693             }
694             break;
695         }
696     }
697 #endif
698
699     return correct;
700 }
701
702 // There are multiple paths in for setting environment stuff.
703 // TEnvironment takes precedence, for what it sets, so sort all this out.
704 // Ideally, the internal code could be made to use TEnvironment, but for
705 // now, translate it to the historically used parameters.
706 void TranslateEnvironment(const TEnvironment* environment, EShMessages& messages, EShSource& source,
707                           EShLanguage& stage, SpvVersion& spvVersion)
708 {
709     // Set up environmental defaults, first ignoring 'environment'.
710     if (messages & EShMsgSpvRules)
711         spvVersion.spv = EShTargetSpv_1_0;
712     if (messages & EShMsgVulkanRules) {
713         spvVersion.vulkan = EShTargetVulkan_1_0;
714         spvVersion.vulkanGlsl = 100;
715     } else if (spvVersion.spv != 0)
716         spvVersion.openGl = 100;
717
718     // Now, override, based on any content set in 'environment'.
719     // 'environment' must be cleared to ESh*None settings when items
720     // are not being set.
721     if (environment != nullptr) {
722         // input language
723         if (environment->input.languageFamily != EShSourceNone) {
724             stage = environment->input.stage;
725             switch (environment->input.dialect) {
726             case EShClientNone:
727                 break;
728             case EShClientVulkan:
729                 spvVersion.vulkanGlsl = environment->input.dialectVersion;
730                 spvVersion.vulkanRelaxed = environment->input.vulkanRulesRelaxed;
731                 break;
732             case EShClientOpenGL:
733                 spvVersion.openGl = environment->input.dialectVersion;
734                 break;
735             case EShClientCount:
736                 assert(0);
737                 break;
738             }
739             switch (environment->input.languageFamily) {
740             case EShSourceNone:
741                 break;
742             case EShSourceGlsl:
743                 source = EShSourceGlsl;
744                 messages = static_cast<EShMessages>(messages & ~EShMsgReadHlsl);
745                 break;
746             case EShSourceHlsl:
747                 source = EShSourceHlsl;
748                 messages = static_cast<EShMessages>(messages | EShMsgReadHlsl);
749                 break;
750             case EShSourceCount:
751                 assert(0);
752                 break;
753             }
754         }
755
756         // client
757         switch (environment->client.client) {
758         case EShClientVulkan:
759             spvVersion.vulkan = environment->client.version;
760             break;
761         default:
762             break;
763         }
764
765         // generated code
766         switch (environment->target.language) {
767         case EshTargetSpv:
768             spvVersion.spv = environment->target.version;
769             break;
770         default:
771             break;
772         }
773     }
774 }
775
776 // Most processes are recorded when set in the intermediate representation,
777 // These are the few that are not.
778 void RecordProcesses(TIntermediate& intermediate, EShMessages messages, const std::string& sourceEntryPointName)
779 {
780     if ((messages & EShMsgRelaxedErrors) != 0)
781         intermediate.addProcess("relaxed-errors");
782     if ((messages & EShMsgSuppressWarnings) != 0)
783         intermediate.addProcess("suppress-warnings");
784     if ((messages & EShMsgKeepUncalled) != 0)
785         intermediate.addProcess("keep-uncalled");
786     if (sourceEntryPointName.size() > 0) {
787         intermediate.addProcess("source-entrypoint");
788         intermediate.addProcessArgument(sourceEntryPointName);
789     }
790 }
791
792 // This is the common setup and cleanup code for PreprocessDeferred and
793 // CompileDeferred.
794 // It takes any callable with a signature of
795 //  bool (TParseContextBase& parseContext, TPpContext& ppContext,
796 //                  TInputScanner& input, bool versionWillBeError,
797 //                  TSymbolTable& , TIntermediate& ,
798 //                  EShOptimizationLevel , EShMessages );
799 // Which returns false if a failure was detected and true otherwise.
800 //
801 template<typename ProcessingContext>
802 bool ProcessDeferred(
803     TCompiler* compiler,
804     const char* const shaderStrings[],
805     const int numStrings,
806     const int* inputLengths,
807     const char* const stringNames[],
808     const char* customPreamble,
809     const EShOptimizationLevel optLevel,
810     const TBuiltInResource* resources,
811     int defaultVersion,  // use 100 for ES environment, 110 for desktop; this is the GLSL version, not SPIR-V or Vulkan
812     EProfile defaultProfile,
813     // set version/profile to defaultVersion/defaultProfile regardless of the #version
814     // directive in the source code
815     bool forceDefaultVersionAndProfile,
816     bool forwardCompatible,     // give errors for use of deprecated features
817     EShMessages messages,       // warnings/errors/AST; things to print out
818     TIntermediate& intermediate, // returned tree, etc.
819     ProcessingContext& processingContext,
820     bool requireNonempty,
821     TShader::Includer& includer,
822     const std::string sourceEntryPointName = "",
823     const TEnvironment* environment = nullptr)  // optional way of fully setting all versions, overriding the above
824 {
825     // This must be undone (.pop()) by the caller, after it finishes consuming the created tree.
826     GetThreadPoolAllocator().push();
827
828     if (numStrings == 0)
829         return true;
830
831     // Move to length-based strings, rather than null-terminated strings.
832     // Also, add strings to include the preamble and to ensure the shader is not null,
833     // which lets the grammar accept what was a null (post preprocessing) shader.
834     //
835     // Shader will look like
836     //   string 0:                system preamble
837     //   string 1:                custom preamble
838     //   string 2...numStrings+1: user's shader
839     //   string numStrings+2:     "int;"
840     const int numPre = 2;
841     const int numPost = requireNonempty? 1 : 0;
842     const int numTotal = numPre + numStrings + numPost;
843     std::unique_ptr<size_t[]> lengths(new size_t[numTotal]);
844     std::unique_ptr<const char*[]> strings(new const char*[numTotal]);
845     std::unique_ptr<const char*[]> names(new const char*[numTotal]);
846     for (int s = 0; s < numStrings; ++s) {
847         strings[s + numPre] = shaderStrings[s];
848         if (inputLengths == nullptr || inputLengths[s] < 0)
849             lengths[s + numPre] = strlen(shaderStrings[s]);
850         else
851             lengths[s + numPre] = inputLengths[s];
852     }
853     if (stringNames != nullptr) {
854         for (int s = 0; s < numStrings; ++s)
855             names[s + numPre] = stringNames[s];
856     } else {
857         for (int s = 0; s < numStrings; ++s)
858             names[s + numPre] = nullptr;
859     }
860
861     // Get all the stages, languages, clients, and other environment
862     // stuff sorted out.
863     EShSource sourceGuess = (messages & EShMsgReadHlsl) != 0 ? EShSourceHlsl : EShSourceGlsl;
864     SpvVersion spvVersion;
865     EShLanguage stage = compiler->getLanguage();
866     TranslateEnvironment(environment, messages, sourceGuess, stage, spvVersion);
867 #ifdef ENABLE_HLSL
868     EShSource source = sourceGuess;
869     if (environment != nullptr && environment->target.hlslFunctionality1)
870         intermediate.setHlslFunctionality1();
871 #else
872     const EShSource source = EShSourceGlsl;
873 #endif
874     // First, without using the preprocessor or parser, find the #version, so we know what
875     // symbol tables, processing rules, etc. to set up.  This does not need the extra strings
876     // outlined above, just the user shader, after the system and user preambles.
877     glslang::TInputScanner userInput(numStrings, &strings[numPre], &lengths[numPre]);
878     int version = 0;
879     EProfile profile = ENoProfile;
880     bool versionNotFirstToken = false;
881     bool versionNotFirst = (source == EShSourceHlsl)
882                                 ? true
883                                 : userInput.scanVersion(version, profile, versionNotFirstToken);
884     bool versionNotFound = version == 0;
885     if (forceDefaultVersionAndProfile && source == EShSourceGlsl) {
886 #if !defined(GLSLANG_WEB) && !defined(GLSLANG_ANGLE)
887         if (! (messages & EShMsgSuppressWarnings) && ! versionNotFound &&
888             (version != defaultVersion || profile != defaultProfile)) {
889             compiler->infoSink.info << "Warning, (version, profile) forced to be ("
890                                     << defaultVersion << ", " << ProfileName(defaultProfile)
891                                     << "), while in source code it is ("
892                                     << version << ", " << ProfileName(profile) << ")\n";
893         }
894 #endif
895         if (versionNotFound) {
896             versionNotFirstToken = false;
897             versionNotFirst = false;
898             versionNotFound = false;
899         }
900         version = defaultVersion;
901         profile = defaultProfile;
902     }
903
904     bool goodVersion = DeduceVersionProfile(compiler->infoSink, stage,
905                                             versionNotFirst, defaultVersion, source, version, profile, spvVersion);
906 #ifdef GLSLANG_WEB
907     profile = EEsProfile;
908     version = 310;
909 #elif defined(GLSLANG_ANGLE)
910     profile = ECoreProfile;
911     version = 450;
912 #endif
913
914     bool versionWillBeError = (versionNotFound || (profile == EEsProfile && version >= 300 && versionNotFirst));
915 #if !defined(GLSLANG_WEB) && !defined(GLSLANG_ANGLE)
916     bool warnVersionNotFirst = false;
917     if (! versionWillBeError && versionNotFirstToken) {
918         if (messages & EShMsgRelaxedErrors)
919             warnVersionNotFirst = true;
920         else
921             versionWillBeError = true;
922     }
923 #endif
924
925     intermediate.setSource(source);
926     intermediate.setVersion(version);
927     intermediate.setProfile(profile);
928     intermediate.setSpv(spvVersion);
929     RecordProcesses(intermediate, messages, sourceEntryPointName);
930     if (spvVersion.vulkan > 0)
931         intermediate.setOriginUpperLeft();
932 #ifdef ENABLE_HLSL
933     if ((messages & EShMsgHlslOffsets) || source == EShSourceHlsl)
934         intermediate.setHlslOffsets();
935 #endif
936     if (messages & EShMsgDebugInfo) {
937         intermediate.setSourceFile(names[numPre]);
938         for (int s = 0; s < numStrings; ++s) {
939             // The string may not be null-terminated, so make sure we provide
940             // the length along with the string.
941             intermediate.addSourceText(strings[numPre + s], lengths[numPre + s]);
942         }
943     }
944     SetupBuiltinSymbolTable(version, profile, spvVersion, source);
945
946     TSymbolTable* cachedTable = SharedSymbolTables[MapVersionToIndex(version)]
947                                                   [MapSpvVersionToIndex(spvVersion)]
948                                                   [MapProfileToIndex(profile)]
949                                                   [MapSourceToIndex(source)]
950                                                   [stage];
951
952     // Dynamically allocate the symbol table so we can control when it is deallocated WRT the pool.
953     std::unique_ptr<TSymbolTable> symbolTable(new TSymbolTable);
954     if (cachedTable)
955         symbolTable->adoptLevels(*cachedTable);
956
957     if (intermediate.getUniqueId() != 0)
958         symbolTable->overwriteUniqueId(intermediate.getUniqueId());
959
960     // Add built-in symbols that are potentially context dependent;
961     // they get popped again further down.
962     if (! AddContextSpecificSymbols(resources, compiler->infoSink, *symbolTable, version, profile, spvVersion,
963                                     stage, source)) {
964         return false;
965     }
966
967     if (messages & EShMsgBuiltinSymbolTable)
968         DumpBuiltinSymbolTable(compiler->infoSink, *symbolTable);
969
970     //
971     // Now we can process the full shader under proper symbols and rules.
972     //
973
974     std::unique_ptr<TParseContextBase> parseContext(CreateParseContext(*symbolTable, intermediate, version, profile, source,
975                                                     stage, compiler->infoSink,
976                                                     spvVersion, forwardCompatible, messages, false, sourceEntryPointName));
977     TPpContext ppContext(*parseContext, names[numPre] ? names[numPre] : "", includer);
978
979     // only GLSL (bison triggered, really) needs an externally set scan context
980     glslang::TScanContext scanContext(*parseContext);
981     if (source == EShSourceGlsl)
982         parseContext->setScanContext(&scanContext);
983
984     parseContext->setPpContext(&ppContext);
985     parseContext->setLimits(*resources);
986     if (! goodVersion)
987         parseContext->addError();
988 #if !defined(GLSLANG_WEB) && !defined(GLSLANG_ANGLE)
989     if (warnVersionNotFirst) {
990         TSourceLoc loc;
991         loc.init();
992         parseContext->warn(loc, "Illegal to have non-comment, non-whitespace tokens before #version", "#version", "");
993     }
994 #endif
995
996     parseContext->initializeExtensionBehavior();
997
998     // Fill in the strings as outlined above.
999     std::string preamble;
1000     parseContext->getPreamble(preamble);
1001     strings[0] = preamble.c_str();
1002     lengths[0] = strlen(strings[0]);
1003     names[0] = nullptr;
1004     strings[1] = customPreamble;
1005     lengths[1] = strlen(strings[1]);
1006     names[1] = nullptr;
1007     assert(2 == numPre);
1008     if (requireNonempty) {
1009         const int postIndex = numStrings + numPre;
1010         strings[postIndex] = "\n int;";
1011         lengths[postIndex] = strlen(strings[numStrings + numPre]);
1012         names[postIndex] = nullptr;
1013     }
1014     TInputScanner fullInput(numStrings + numPre + numPost, strings.get(), lengths.get(), names.get(), numPre, numPost);
1015
1016     // Push a new symbol allocation scope that will get used for the shader's globals.
1017     symbolTable->push();
1018
1019     bool success = processingContext(*parseContext, ppContext, fullInput,
1020                                      versionWillBeError, *symbolTable,
1021                                      intermediate, optLevel, messages);
1022     intermediate.setUniqueId(symbolTable->getMaxSymbolId());
1023     return success;
1024 }
1025
1026 #if !defined(GLSLANG_WEB) && !defined(GLSLANG_ANGLE)
1027
1028 // Responsible for keeping track of the most recent source string and line in
1029 // the preprocessor and outputting newlines appropriately if the source string
1030 // or line changes.
1031 class SourceLineSynchronizer {
1032 public:
1033     SourceLineSynchronizer(const std::function<int()>& lastSourceIndex,
1034                            std::string* output)
1035       : getLastSourceIndex(lastSourceIndex), output(output), lastSource(-1), lastLine(0) {}
1036 //    SourceLineSynchronizer(const SourceLineSynchronizer&) = delete;
1037 //    SourceLineSynchronizer& operator=(const SourceLineSynchronizer&) = delete;
1038
1039     // Sets the internally tracked source string index to that of the most
1040     // recently read token. If we switched to a new source string, returns
1041     // true and inserts a newline. Otherwise, returns false and outputs nothing.
1042     bool syncToMostRecentString() {
1043         if (getLastSourceIndex() != lastSource) {
1044             // After switching to a new source string, we need to reset lastLine
1045             // because line number resets every time a new source string is
1046             // used. We also need to output a newline to separate the output
1047             // from the previous source string (if there is one).
1048             if (lastSource != -1 || lastLine != 0)
1049                 *output += '\n';
1050             lastSource = getLastSourceIndex();
1051             lastLine = -1;
1052             return true;
1053         }
1054         return false;
1055     }
1056
1057     // Calls syncToMostRecentString() and then sets the internally tracked line
1058     // number to tokenLine. If we switched to a new line, returns true and inserts
1059     // newlines appropriately. Otherwise, returns false and outputs nothing.
1060     bool syncToLine(int tokenLine) {
1061         syncToMostRecentString();
1062         const bool newLineStarted = lastLine < tokenLine;
1063         for (; lastLine < tokenLine; ++lastLine) {
1064             if (lastLine > 0) *output += '\n';
1065         }
1066         return newLineStarted;
1067     }
1068
1069     // Sets the internally tracked line number to newLineNum.
1070     void setLineNum(int newLineNum) { lastLine = newLineNum; }
1071
1072 private:
1073     SourceLineSynchronizer& operator=(const SourceLineSynchronizer&);
1074
1075     // A function for getting the index of the last valid source string we've
1076     // read tokens from.
1077     const std::function<int()> getLastSourceIndex;
1078     // output string for newlines.
1079     std::string* output;
1080     // lastSource is the source string index (starting from 0) of the last token
1081     // processed. It is tracked in order for newlines to be inserted when a new
1082     // source string starts. -1 means we haven't started processing any source
1083     // string.
1084     int lastSource;
1085     // lastLine is the line number (starting from 1) of the last token processed.
1086     // It is tracked in order for newlines to be inserted when a token appears
1087     // on a new line. 0 means we haven't started processing any line in the
1088     // current source string.
1089     int lastLine;
1090 };
1091
1092 // DoPreprocessing is a valid ProcessingContext template argument,
1093 // which only performs the preprocessing step of compilation.
1094 // It places the result in the "string" argument to its constructor.
1095 //
1096 // This is not an officially supported or fully working path.
1097 struct DoPreprocessing {
1098     explicit DoPreprocessing(std::string* string): outputString(string) {}
1099     bool operator()(TParseContextBase& parseContext, TPpContext& ppContext,
1100                     TInputScanner& input, bool versionWillBeError,
1101                     TSymbolTable&, TIntermediate&,
1102                     EShOptimizationLevel, EShMessages)
1103     {
1104         // This is a list of tokens that do not require a space before or after.
1105         static const std::string unNeededSpaceTokens = ";()[]";
1106         static const std::string noSpaceBeforeTokens = ",";
1107         glslang::TPpToken ppToken;
1108
1109         parseContext.setScanner(&input);
1110         ppContext.setInput(input, versionWillBeError);
1111
1112         std::string outputBuffer;
1113         SourceLineSynchronizer lineSync(
1114             std::bind(&TInputScanner::getLastValidSourceIndex, &input), &outputBuffer);
1115
1116         parseContext.setExtensionCallback([&lineSync, &outputBuffer](
1117             int line, const char* extension, const char* behavior) {
1118                 lineSync.syncToLine(line);
1119                 outputBuffer += "#extension ";
1120                 outputBuffer += extension;
1121                 outputBuffer += " : ";
1122                 outputBuffer += behavior;
1123         });
1124
1125         parseContext.setLineCallback([&lineSync, &outputBuffer, &parseContext](
1126             int curLineNum, int newLineNum, bool hasSource, int sourceNum, const char* sourceName) {
1127             // SourceNum is the number of the source-string that is being parsed.
1128             lineSync.syncToLine(curLineNum);
1129             outputBuffer += "#line ";
1130             outputBuffer += std::to_string(newLineNum);
1131             if (hasSource) {
1132                 outputBuffer += ' ';
1133                 if (sourceName != nullptr) {
1134                     outputBuffer += '\"';
1135                     outputBuffer += sourceName;
1136                     outputBuffer += '\"';
1137                 } else {
1138                     outputBuffer += std::to_string(sourceNum);
1139                 }
1140             }
1141             if (parseContext.lineDirectiveShouldSetNextLine()) {
1142                 // newLineNum is the new line number for the line following the #line
1143                 // directive. So the new line number for the current line is
1144                 newLineNum -= 1;
1145             }
1146             outputBuffer += '\n';
1147             // And we are at the next line of the #line directive now.
1148             lineSync.setLineNum(newLineNum + 1);
1149         });
1150
1151         parseContext.setVersionCallback(
1152             [&lineSync, &outputBuffer](int line, int version, const char* str) {
1153                 lineSync.syncToLine(line);
1154                 outputBuffer += "#version ";
1155                 outputBuffer += std::to_string(version);
1156                 if (str) {
1157                     outputBuffer += ' ';
1158                     outputBuffer += str;
1159                 }
1160             });
1161
1162         parseContext.setPragmaCallback([&lineSync, &outputBuffer](
1163             int line, const glslang::TVector<glslang::TString>& ops) {
1164                 lineSync.syncToLine(line);
1165                 outputBuffer += "#pragma ";
1166                 for(size_t i = 0; i < ops.size(); ++i) {
1167                     outputBuffer += ops[i].c_str();
1168                 }
1169         });
1170
1171         parseContext.setErrorCallback([&lineSync, &outputBuffer](
1172             int line, const char* errorMessage) {
1173                 lineSync.syncToLine(line);
1174                 outputBuffer += "#error ";
1175                 outputBuffer += errorMessage;
1176         });
1177
1178         int lastToken = EndOfInput; // lastToken records the last token processed.
1179         do {
1180             int token = ppContext.tokenize(ppToken);
1181             if (token == EndOfInput)
1182                 break;
1183
1184             bool isNewString = lineSync.syncToMostRecentString();
1185             bool isNewLine = lineSync.syncToLine(ppToken.loc.line);
1186
1187             if (isNewLine) {
1188                 // Don't emit whitespace onto empty lines.
1189                 // Copy any whitespace characters at the start of a line
1190                 // from the input to the output.
1191                 outputBuffer += std::string(ppToken.loc.column - 1, ' ');
1192             }
1193
1194             // Output a space in between tokens, but not at the start of a line,
1195             // and also not around special tokens. This helps with readability
1196             // and consistency.
1197             if (!isNewString && !isNewLine && lastToken != EndOfInput &&
1198                 (unNeededSpaceTokens.find((char)token) == std::string::npos) &&
1199                 (unNeededSpaceTokens.find((char)lastToken) == std::string::npos) &&
1200                 (noSpaceBeforeTokens.find((char)token) == std::string::npos)) {
1201                 outputBuffer += ' ';
1202             }
1203             lastToken = token;
1204             if (token == PpAtomConstString)
1205                 outputBuffer += "\"";
1206             outputBuffer += ppToken.name;
1207             if (token == PpAtomConstString)
1208                 outputBuffer += "\"";
1209         } while (true);
1210         outputBuffer += '\n';
1211         *outputString = std::move(outputBuffer);
1212
1213         bool success = true;
1214         if (parseContext.getNumErrors() > 0) {
1215             success = false;
1216             parseContext.infoSink.info.prefix(EPrefixError);
1217             parseContext.infoSink.info << parseContext.getNumErrors() << " compilation errors.  No code generated.\n\n";
1218         }
1219         return success;
1220     }
1221     std::string* outputString;
1222 };
1223
1224 #endif
1225
1226 // DoFullParse is a valid ProcessingConext template argument for fully
1227 // parsing the shader.  It populates the "intermediate" with the AST.
1228 struct DoFullParse{
1229   bool operator()(TParseContextBase& parseContext, TPpContext& ppContext,
1230                   TInputScanner& fullInput, bool versionWillBeError,
1231                   TSymbolTable&, TIntermediate& intermediate,
1232                   EShOptimizationLevel optLevel, EShMessages messages)
1233     {
1234         bool success = true;
1235         // Parse the full shader.
1236         if (! parseContext.parseShaderStrings(ppContext, fullInput, versionWillBeError))
1237             success = false;
1238
1239         if (success && intermediate.getTreeRoot()) {
1240             if (optLevel == EShOptNoGeneration)
1241                 parseContext.infoSink.info.message(EPrefixNone, "No errors.  No code generation or linking was requested.");
1242             else
1243                 success = intermediate.postProcess(intermediate.getTreeRoot(), parseContext.getLanguage());
1244         } else if (! success) {
1245             parseContext.infoSink.info.prefix(EPrefixError);
1246             parseContext.infoSink.info << parseContext.getNumErrors() << " compilation errors.  No code generated.\n\n";
1247         }
1248
1249 #ifndef GLSLANG_ANGLE
1250         if (messages & EShMsgAST)
1251             intermediate.output(parseContext.infoSink, true);
1252 #endif
1253
1254         return success;
1255     }
1256 };
1257
1258 #if !defined(GLSLANG_WEB) && !defined(GLSLANG_ANGLE)
1259 // Take a single compilation unit, and run the preprocessor on it.
1260 // Return: True if there were no issues found in preprocessing,
1261 //         False if during preprocessing any unknown version, pragmas or
1262 //         extensions were found.
1263 //
1264 // NOTE: Doing just preprocessing to obtain a correct preprocessed shader string
1265 // is not an officially supported or fully working path.
1266 bool PreprocessDeferred(
1267     TCompiler* compiler,
1268     const char* const shaderStrings[],
1269     const int numStrings,
1270     const int* inputLengths,
1271     const char* const stringNames[],
1272     const char* preamble,
1273     const EShOptimizationLevel optLevel,
1274     const TBuiltInResource* resources,
1275     int defaultVersion,         // use 100 for ES environment, 110 for desktop
1276     EProfile defaultProfile,
1277     bool forceDefaultVersionAndProfile,
1278     bool forwardCompatible,     // give errors for use of deprecated features
1279     EShMessages messages,       // warnings/errors/AST; things to print out
1280     TShader::Includer& includer,
1281     TIntermediate& intermediate, // returned tree, etc.
1282     std::string* outputString,
1283     TEnvironment* environment = nullptr)
1284 {
1285     DoPreprocessing parser(outputString);
1286     return ProcessDeferred(compiler, shaderStrings, numStrings, inputLengths, stringNames,
1287                            preamble, optLevel, resources, defaultVersion,
1288                            defaultProfile, forceDefaultVersionAndProfile,
1289                            forwardCompatible, messages, intermediate, parser,
1290                            false, includer, "", environment);
1291 }
1292 #endif
1293
1294 //
1295 // do a partial compile on the given strings for a single compilation unit
1296 // for a potential deferred link into a single stage (and deferred full compile of that
1297 // stage through machine-dependent compilation).
1298 //
1299 // all preprocessing, parsing, semantic checks, etc. for a single compilation unit
1300 // are done here.
1301 //
1302 // return:  the tree and other information is filled into the intermediate argument,
1303 //          and true is returned by the function for success.
1304 //
1305 bool CompileDeferred(
1306     TCompiler* compiler,
1307     const char* const shaderStrings[],
1308     const int numStrings,
1309     const int* inputLengths,
1310     const char* const stringNames[],
1311     const char* preamble,
1312     const EShOptimizationLevel optLevel,
1313     const TBuiltInResource* resources,
1314     int defaultVersion,         // use 100 for ES environment, 110 for desktop
1315     EProfile defaultProfile,
1316     bool forceDefaultVersionAndProfile,
1317     bool forwardCompatible,     // give errors for use of deprecated features
1318     EShMessages messages,       // warnings/errors/AST; things to print out
1319     TIntermediate& intermediate,// returned tree, etc.
1320     TShader::Includer& includer,
1321     const std::string sourceEntryPointName = "",
1322     TEnvironment* environment = nullptr)
1323 {
1324     DoFullParse parser;
1325     return ProcessDeferred(compiler, shaderStrings, numStrings, inputLengths, stringNames,
1326                            preamble, optLevel, resources, defaultVersion,
1327                            defaultProfile, forceDefaultVersionAndProfile,
1328                            forwardCompatible, messages, intermediate, parser,
1329                            true, includer, sourceEntryPointName, environment);
1330 }
1331
1332 } // end anonymous namespace for local functions
1333
1334 //
1335 // ShInitialize() should be called exactly once per process, not per thread.
1336 //
1337 int ShInitialize()
1338 {
1339     glslang::InitGlobalLock();
1340
1341     if (! InitProcess())
1342         return 0;
1343
1344     glslang::GetGlobalLock();
1345     ++NumberOfClients;
1346     glslang::ReleaseGlobalLock();
1347
1348     if (PerProcessGPA == nullptr)
1349         PerProcessGPA = new TPoolAllocator();
1350
1351     glslang::TScanContext::fillInKeywordMap();
1352 #ifdef ENABLE_HLSL
1353     glslang::HlslScanContext::fillInKeywordMap();
1354 #endif
1355
1356     return 1;
1357 }
1358
1359 //
1360 // Driver calls these to create and destroy compiler/linker
1361 // objects.
1362 //
1363
1364 ShHandle ShConstructCompiler(const EShLanguage language, int debugOptions)
1365 {
1366     if (!InitThread())
1367         return 0;
1368
1369     TShHandleBase* base = static_cast<TShHandleBase*>(ConstructCompiler(language, debugOptions));
1370
1371     return reinterpret_cast<void*>(base);
1372 }
1373
1374 ShHandle ShConstructLinker(const EShExecutable executable, int debugOptions)
1375 {
1376     if (!InitThread())
1377         return 0;
1378
1379     TShHandleBase* base = static_cast<TShHandleBase*>(ConstructLinker(executable, debugOptions));
1380
1381     return reinterpret_cast<void*>(base);
1382 }
1383
1384 ShHandle ShConstructUniformMap()
1385 {
1386     if (!InitThread())
1387         return 0;
1388
1389     TShHandleBase* base = static_cast<TShHandleBase*>(ConstructUniformMap());
1390
1391     return reinterpret_cast<void*>(base);
1392 }
1393
1394 void ShDestruct(ShHandle handle)
1395 {
1396     if (handle == 0)
1397         return;
1398
1399     TShHandleBase* base = static_cast<TShHandleBase*>(handle);
1400
1401     if (base->getAsCompiler())
1402         DeleteCompiler(base->getAsCompiler());
1403     else if (base->getAsLinker())
1404         DeleteLinker(base->getAsLinker());
1405     else if (base->getAsUniformMap())
1406         DeleteUniformMap(base->getAsUniformMap());
1407 }
1408
1409 //
1410 // Cleanup symbol tables
1411 //
1412 int ShFinalize()
1413 {
1414     glslang::GetGlobalLock();
1415     --NumberOfClients;
1416     assert(NumberOfClients >= 0);
1417     bool finalize = NumberOfClients == 0;
1418     glslang::ReleaseGlobalLock();
1419     if (! finalize)
1420         return 1;
1421
1422     for (int version = 0; version < VersionCount; ++version) {
1423         for (int spvVersion = 0; spvVersion < SpvVersionCount; ++spvVersion) {
1424             for (int p = 0; p < ProfileCount; ++p) {
1425                 for (int source = 0; source < SourceCount; ++source) {
1426                     for (int stage = 0; stage < EShLangCount; ++stage) {
1427                         delete SharedSymbolTables[version][spvVersion][p][source][stage];
1428                         SharedSymbolTables[version][spvVersion][p][source][stage] = 0;
1429                     }
1430                 }
1431             }
1432         }
1433     }
1434
1435     for (int version = 0; version < VersionCount; ++version) {
1436         for (int spvVersion = 0; spvVersion < SpvVersionCount; ++spvVersion) {
1437             for (int p = 0; p < ProfileCount; ++p) {
1438                 for (int source = 0; source < SourceCount; ++source) {
1439                     for (int pc = 0; pc < EPcCount; ++pc) {
1440                         delete CommonSymbolTable[version][spvVersion][p][source][pc];
1441                         CommonSymbolTable[version][spvVersion][p][source][pc] = 0;
1442                     }
1443                 }
1444             }
1445         }
1446     }
1447
1448     if (PerProcessGPA != nullptr) {
1449         delete PerProcessGPA;
1450         PerProcessGPA = nullptr;
1451     }
1452
1453     glslang::TScanContext::deleteKeywordMap();
1454 #ifdef ENABLE_HLSL
1455     glslang::HlslScanContext::deleteKeywordMap();
1456 #endif
1457
1458     return 1;
1459 }
1460
1461 //
1462 // Do a full compile on the given strings for a single compilation unit
1463 // forming a complete stage.  The result of the machine dependent compilation
1464 // is left in the provided compile object.
1465 //
1466 // Return:  The return value is really boolean, indicating
1467 // success (1) or failure (0).
1468 //
1469 int ShCompile(
1470     const ShHandle handle,
1471     const char* const shaderStrings[],
1472     const int numStrings,
1473     const int* inputLengths,
1474     const EShOptimizationLevel optLevel,
1475     const TBuiltInResource* resources,
1476     int /*debugOptions*/,
1477     int defaultVersion,        // use 100 for ES environment, 110 for desktop
1478     bool forwardCompatible,    // give errors for use of deprecated features
1479     EShMessages messages       // warnings/errors/AST; things to print out
1480     )
1481 {
1482     // Map the generic handle to the C++ object
1483     if (handle == 0)
1484         return 0;
1485
1486     TShHandleBase* base = reinterpret_cast<TShHandleBase*>(handle);
1487     TCompiler* compiler = base->getAsCompiler();
1488     if (compiler == 0)
1489         return 0;
1490
1491     SetThreadPoolAllocator(compiler->getPool());
1492
1493     compiler->infoSink.info.erase();
1494     compiler->infoSink.debug.erase();
1495
1496     TIntermediate intermediate(compiler->getLanguage());
1497     TShader::ForbidIncluder includer;
1498     bool success = CompileDeferred(compiler, shaderStrings, numStrings, inputLengths, nullptr,
1499                                    "", optLevel, resources, defaultVersion, ENoProfile, false,
1500                                    forwardCompatible, messages, intermediate, includer);
1501
1502     //
1503     // Call the machine dependent compiler
1504     //
1505     if (success && intermediate.getTreeRoot() && optLevel != EShOptNoGeneration)
1506         success = compiler->compile(intermediate.getTreeRoot(), intermediate.getVersion(), intermediate.getProfile());
1507
1508     intermediate.removeTree();
1509
1510     // Throw away all the temporary memory used by the compilation process.
1511     // The push was done in the CompileDeferred() call above.
1512     GetThreadPoolAllocator().pop();
1513
1514     return success ? 1 : 0;
1515 }
1516
1517 //
1518 // Link the given compile objects.
1519 //
1520 // Return:  The return value of is really boolean, indicating
1521 // success or failure.
1522 //
1523 int ShLinkExt(
1524     const ShHandle linkHandle,
1525     const ShHandle compHandles[],
1526     const int numHandles)
1527 {
1528     if (linkHandle == 0 || numHandles == 0)
1529         return 0;
1530
1531     THandleList cObjects;
1532
1533     for (int i = 0; i < numHandles; ++i) {
1534         if (compHandles[i] == 0)
1535             return 0;
1536         TShHandleBase* base = reinterpret_cast<TShHandleBase*>(compHandles[i]);
1537         if (base->getAsLinker()) {
1538             cObjects.push_back(base->getAsLinker());
1539         }
1540         if (base->getAsCompiler())
1541             cObjects.push_back(base->getAsCompiler());
1542
1543         if (cObjects[i] == 0)
1544             return 0;
1545     }
1546
1547     TShHandleBase* base = reinterpret_cast<TShHandleBase*>(linkHandle);
1548     TLinker* linker = static_cast<TLinker*>(base->getAsLinker());
1549
1550     SetThreadPoolAllocator(linker->getPool());
1551
1552     if (linker == 0)
1553         return 0;
1554
1555     linker->infoSink.info.erase();
1556
1557     for (int i = 0; i < numHandles; ++i) {
1558         if (cObjects[i]->getAsCompiler()) {
1559             if (! cObjects[i]->getAsCompiler()->linkable()) {
1560                 linker->infoSink.info.message(EPrefixError, "Not all shaders have valid object code.");
1561                 return 0;
1562             }
1563         }
1564     }
1565
1566     bool ret = linker->link(cObjects);
1567
1568     return ret ? 1 : 0;
1569 }
1570
1571 //
1572 // ShSetEncrpytionMethod is a place-holder for specifying
1573 // how source code is encrypted.
1574 //
1575 void ShSetEncryptionMethod(ShHandle handle)
1576 {
1577     if (handle == 0)
1578         return;
1579 }
1580
1581 //
1582 // Return any compiler/linker/uniformmap log of messages for the application.
1583 //
1584 const char* ShGetInfoLog(const ShHandle handle)
1585 {
1586     if (handle == 0)
1587         return 0;
1588
1589     TShHandleBase* base = static_cast<TShHandleBase*>(handle);
1590     TInfoSink* infoSink;
1591
1592     if (base->getAsCompiler())
1593         infoSink = &(base->getAsCompiler()->getInfoSink());
1594     else if (base->getAsLinker())
1595         infoSink = &(base->getAsLinker()->getInfoSink());
1596     else
1597         return 0;
1598
1599     infoSink->info << infoSink->debug.c_str();
1600     return infoSink->info.c_str();
1601 }
1602
1603 //
1604 // Return the resulting binary code from the link process.  Structure
1605 // is machine dependent.
1606 //
1607 const void* ShGetExecutable(const ShHandle handle)
1608 {
1609     if (handle == 0)
1610         return 0;
1611
1612     TShHandleBase* base = reinterpret_cast<TShHandleBase*>(handle);
1613
1614     TLinker* linker = static_cast<TLinker*>(base->getAsLinker());
1615     if (linker == 0)
1616         return 0;
1617
1618     return linker->getObjectCode();
1619 }
1620
1621 //
1622 // Let the linker know where the application said it's attributes are bound.
1623 // The linker does not use these values, they are remapped by the ICD or
1624 // hardware.  It just needs them to know what's aliased.
1625 //
1626 // Return:  The return value of is really boolean, indicating
1627 // success or failure.
1628 //
1629 int ShSetVirtualAttributeBindings(const ShHandle handle, const ShBindingTable* table)
1630 {
1631     if (handle == 0)
1632         return 0;
1633
1634     TShHandleBase* base = reinterpret_cast<TShHandleBase*>(handle);
1635     TLinker* linker = static_cast<TLinker*>(base->getAsLinker());
1636
1637     if (linker == 0)
1638         return 0;
1639
1640     linker->setAppAttributeBindings(table);
1641
1642     return 1;
1643 }
1644
1645 //
1646 // Let the linker know where the predefined attributes have to live.
1647 //
1648 int ShSetFixedAttributeBindings(const ShHandle handle, const ShBindingTable* table)
1649 {
1650     if (handle == 0)
1651         return 0;
1652
1653     TShHandleBase* base = reinterpret_cast<TShHandleBase*>(handle);
1654     TLinker* linker = static_cast<TLinker*>(base->getAsLinker());
1655
1656     if (linker == 0)
1657         return 0;
1658
1659     linker->setFixedAttributeBindings(table);
1660     return 1;
1661 }
1662
1663 //
1664 // Some attribute locations are off-limits to the linker...
1665 //
1666 int ShExcludeAttributes(const ShHandle handle, int *attributes, int count)
1667 {
1668     if (handle == 0)
1669         return 0;
1670
1671     TShHandleBase* base = reinterpret_cast<TShHandleBase*>(handle);
1672     TLinker* linker = static_cast<TLinker*>(base->getAsLinker());
1673     if (linker == 0)
1674         return 0;
1675
1676     linker->setExcludedAttributes(attributes, count);
1677
1678     return 1;
1679 }
1680
1681 //
1682 // Return the index for OpenGL to use for knowing where a uniform lives.
1683 //
1684 // Return:  The return value of is really boolean, indicating
1685 // success or failure.
1686 //
1687 int ShGetUniformLocation(const ShHandle handle, const char* name)
1688 {
1689     if (handle == 0)
1690         return -1;
1691
1692     TShHandleBase* base = reinterpret_cast<TShHandleBase*>(handle);
1693     TUniformMap* uniformMap= base->getAsUniformMap();
1694     if (uniformMap == 0)
1695         return -1;
1696
1697     return uniformMap->getLocation(name);
1698 }
1699
1700 ////////////////////////////////////////////////////////////////////////////////////////////
1701 //
1702 // Deferred-Lowering C++ Interface
1703 // -----------------------------------
1704 //
1705 // Below is a new alternate C++ interface that might potentially replace the above
1706 // opaque handle-based interface.
1707 //
1708 // See more detailed comment in ShaderLang.h
1709 //
1710
1711 namespace glslang {
1712
1713 Version GetVersion()
1714 {
1715     Version version;
1716     version.major = GLSLANG_VERSION_MAJOR;
1717     version.minor = GLSLANG_VERSION_MINOR;
1718     version.patch = GLSLANG_VERSION_PATCH;
1719     version.flavor = GLSLANG_VERSION_FLAVOR;
1720     return version;
1721 }
1722
1723 #define QUOTE(s) #s
1724 #define STR(n) QUOTE(n)
1725
1726 const char* GetEsslVersionString()
1727 {
1728     return "OpenGL ES GLSL 3.20 glslang Khronos. " STR(GLSLANG_VERSION_MAJOR) "." STR(GLSLANG_VERSION_MINOR) "." STR(
1729         GLSLANG_VERSION_PATCH) GLSLANG_VERSION_FLAVOR;
1730 }
1731
1732 const char* GetGlslVersionString()
1733 {
1734     return "4.60 glslang Khronos. " STR(GLSLANG_VERSION_MAJOR) "." STR(GLSLANG_VERSION_MINOR) "." STR(
1735         GLSLANG_VERSION_PATCH) GLSLANG_VERSION_FLAVOR;
1736 }
1737
1738 int GetKhronosToolId()
1739 {
1740     return 8;
1741 }
1742
1743 bool InitializeProcess()
1744 {
1745     return ShInitialize() != 0;
1746 }
1747
1748 void FinalizeProcess()
1749 {
1750     ShFinalize();
1751 }
1752
1753 class TDeferredCompiler : public TCompiler {
1754 public:
1755     TDeferredCompiler(EShLanguage s, TInfoSink& i) : TCompiler(s, i) { }
1756     virtual bool compile(TIntermNode*, int = 0, EProfile = ENoProfile) { return true; }
1757 };
1758
1759 TShader::TShader(EShLanguage s)
1760     : stage(s), lengths(nullptr), stringNames(nullptr), preamble("")
1761 {
1762     pool = new TPoolAllocator;
1763     infoSink = new TInfoSink;
1764     compiler = new TDeferredCompiler(stage, *infoSink);
1765     intermediate = new TIntermediate(s);
1766
1767     // clear environment (avoid constructors in them for use in a C interface)
1768     environment.input.languageFamily = EShSourceNone;
1769     environment.input.dialect = EShClientNone;
1770     environment.input.vulkanRulesRelaxed = false;
1771     environment.client.client = EShClientNone;
1772     environment.target.language = EShTargetNone;
1773     environment.target.hlslFunctionality1 = false;
1774 }
1775
1776 TShader::~TShader()
1777 {
1778     delete infoSink;
1779     delete compiler;
1780     delete intermediate;
1781     delete pool;
1782 }
1783
1784 void TShader::setStrings(const char* const* s, int n)
1785 {
1786     strings = s;
1787     numStrings = n;
1788     lengths = nullptr;
1789 }
1790
1791 void TShader::setStringsWithLengths(const char* const* s, const int* l, int n)
1792 {
1793     strings = s;
1794     numStrings = n;
1795     lengths = l;
1796 }
1797
1798 void TShader::setStringsWithLengthsAndNames(
1799     const char* const* s, const int* l, const char* const* names, int n)
1800 {
1801     strings = s;
1802     numStrings = n;
1803     lengths = l;
1804     stringNames = names;
1805 }
1806
1807 void TShader::setEntryPoint(const char* entryPoint)
1808 {
1809     intermediate->setEntryPointName(entryPoint);
1810 }
1811
1812 void TShader::setSourceEntryPoint(const char* name)
1813 {
1814     sourceEntryPointName = name;
1815 }
1816
1817 // Log initial settings and transforms.
1818 // See comment for class TProcesses.
1819 void TShader::addProcesses(const std::vector<std::string>& p)
1820 {
1821     intermediate->addProcesses(p);
1822 }
1823
1824 void  TShader::setUniqueId(unsigned long long id)
1825 {
1826     intermediate->setUniqueId(id);
1827 }
1828
1829 void TShader::setInvertY(bool invert)                   { intermediate->setInvertY(invert); }
1830 void TShader::setNanMinMaxClamp(bool useNonNan)         { intermediate->setNanMinMaxClamp(useNonNan); }
1831
1832 #ifndef GLSLANG_WEB
1833
1834 // Set binding base for given resource type
1835 void TShader::setShiftBinding(TResourceType res, unsigned int base) {
1836     intermediate->setShiftBinding(res, base);
1837 }
1838
1839 // Set binding base for given resource type for a given binding set.
1840 void TShader::setShiftBindingForSet(TResourceType res, unsigned int base, unsigned int set) {
1841     intermediate->setShiftBindingForSet(res, base, set);
1842 }
1843
1844 // Set binding base for sampler types
1845 void TShader::setShiftSamplerBinding(unsigned int base) { setShiftBinding(EResSampler, base); }
1846 // Set binding base for texture types (SRV)
1847 void TShader::setShiftTextureBinding(unsigned int base) { setShiftBinding(EResTexture, base); }
1848 // Set binding base for image types
1849 void TShader::setShiftImageBinding(unsigned int base)   { setShiftBinding(EResImage, base); }
1850 // Set binding base for uniform buffer objects (CBV)
1851 void TShader::setShiftUboBinding(unsigned int base)     { setShiftBinding(EResUbo, base); }
1852 // Synonym for setShiftUboBinding, to match HLSL language.
1853 void TShader::setShiftCbufferBinding(unsigned int base) { setShiftBinding(EResUbo, base); }
1854 // Set binding base for UAV (unordered access view)
1855 void TShader::setShiftUavBinding(unsigned int base)     { setShiftBinding(EResUav, base); }
1856 // Set binding base for SSBOs
1857 void TShader::setShiftSsboBinding(unsigned int base)    { setShiftBinding(EResSsbo, base); }
1858 // Enables binding automapping using TIoMapper
1859 void TShader::setAutoMapBindings(bool map)              { intermediate->setAutoMapBindings(map); }
1860 // Enables position.Y output negation in vertex shader
1861
1862 // Fragile: currently within one stage: simple auto-assignment of location
1863 void TShader::setAutoMapLocations(bool map)             { intermediate->setAutoMapLocations(map); }
1864 void TShader::addUniformLocationOverride(const char* name, int loc)
1865 {
1866     intermediate->addUniformLocationOverride(name, loc);
1867 }
1868 void TShader::setUniformLocationBase(int base)
1869 {
1870     intermediate->setUniformLocationBase(base);
1871 }
1872 void TShader::setNoStorageFormat(bool useUnknownFormat) { intermediate->setNoStorageFormat(useUnknownFormat); }
1873 void TShader::setResourceSetBinding(const std::vector<std::string>& base)   { intermediate->setResourceSetBinding(base); }
1874 void TShader::setTextureSamplerTransformMode(EShTextureSamplerTransformMode mode) { intermediate->setTextureSamplerTransformMode(mode); }
1875 #endif
1876
1877 void TShader::addBlockStorageOverride(const char* nameStr, TBlockStorageClass backing) { intermediate->addBlockStorageOverride(nameStr, backing); }
1878
1879 void TShader::setGlobalUniformBlockName(const char* name) { intermediate->setGlobalUniformBlockName(name); }
1880 void TShader::setGlobalUniformSet(unsigned int set) { intermediate->setGlobalUniformSet(set); }
1881 void TShader::setGlobalUniformBinding(unsigned int binding) { intermediate->setGlobalUniformBinding(binding); }
1882
1883 void TShader::setAtomicCounterBlockName(const char* name) { intermediate->setAtomicCounterBlockName(name); }
1884 void TShader::setAtomicCounterBlockSet(unsigned int set) { intermediate->setAtomicCounterBlockSet(set); }
1885
1886 #ifdef ENABLE_HLSL
1887 // See comment above TDefaultHlslIoMapper in iomapper.cpp:
1888 void TShader::setHlslIoMapping(bool hlslIoMap)          { intermediate->setHlslIoMapping(hlslIoMap); }
1889 void TShader::setFlattenUniformArrays(bool flatten)     { intermediate->setFlattenUniformArrays(flatten); }
1890 #endif
1891
1892 //
1893 // Turn the shader strings into a parse tree in the TIntermediate.
1894 //
1895 // Returns true for success.
1896 //
1897 bool TShader::parse(const TBuiltInResource* builtInResources, int defaultVersion, EProfile defaultProfile, bool forceDefaultVersionAndProfile,
1898                     bool forwardCompatible, EShMessages messages, Includer& includer)
1899 {
1900     if (! InitThread())
1901         return false;
1902     SetThreadPoolAllocator(pool);
1903
1904     if (! preamble)
1905         preamble = "";
1906
1907     return CompileDeferred(compiler, strings, numStrings, lengths, stringNames,
1908                            preamble, EShOptNone, builtInResources, defaultVersion,
1909                            defaultProfile, forceDefaultVersionAndProfile,
1910                            forwardCompatible, messages, *intermediate, includer, sourceEntryPointName,
1911                            &environment);
1912 }
1913
1914 #if !defined(GLSLANG_WEB) && !defined(GLSLANG_ANGLE)
1915 // Fill in a string with the result of preprocessing ShaderStrings
1916 // Returns true if all extensions, pragmas and version strings were valid.
1917 //
1918 // NOTE: Doing just preprocessing to obtain a correct preprocessed shader string
1919 // is not an officially supported or fully working path.
1920 bool TShader::preprocess(const TBuiltInResource* builtInResources,
1921                          int defaultVersion, EProfile defaultProfile,
1922                          bool forceDefaultVersionAndProfile,
1923                          bool forwardCompatible, EShMessages message,
1924                          std::string* output_string,
1925                          Includer& includer)
1926 {
1927     if (! InitThread())
1928         return false;
1929     SetThreadPoolAllocator(pool);
1930
1931     if (! preamble)
1932         preamble = "";
1933
1934     return PreprocessDeferred(compiler, strings, numStrings, lengths, stringNames, preamble,
1935                               EShOptNone, builtInResources, defaultVersion,
1936                               defaultProfile, forceDefaultVersionAndProfile,
1937                               forwardCompatible, message, includer, *intermediate, output_string,
1938                               &environment);
1939 }
1940 #endif
1941
1942 const char* TShader::getInfoLog()
1943 {
1944     return infoSink->info.c_str();
1945 }
1946
1947 const char* TShader::getInfoDebugLog()
1948 {
1949     return infoSink->debug.c_str();
1950 }
1951
1952 TProgram::TProgram() :
1953 #if !defined(GLSLANG_WEB) && !defined(GLSLANG_ANGLE)
1954     reflection(0),
1955 #endif
1956     linked(false)
1957 {
1958     pool = new TPoolAllocator;
1959     infoSink = new TInfoSink;
1960     for (int s = 0; s < EShLangCount; ++s) {
1961         intermediate[s] = 0;
1962         newedIntermediate[s] = false;
1963     }
1964 }
1965
1966 TProgram::~TProgram()
1967 {
1968     delete infoSink;
1969 #if !defined(GLSLANG_WEB) && !defined(GLSLANG_ANGLE)
1970     delete reflection;
1971 #endif
1972
1973     for (int s = 0; s < EShLangCount; ++s)
1974         if (newedIntermediate[s])
1975             delete intermediate[s];
1976
1977     delete pool;
1978 }
1979
1980 //
1981 // Merge the compilation units within each stage into a single TIntermediate.
1982 // All starting compilation units need to be the result of calling TShader::parse().
1983 //
1984 // Return true for success.
1985 //
1986 bool TProgram::link(EShMessages messages)
1987 {
1988     if (linked)
1989         return false;
1990     linked = true;
1991
1992     bool error = false;
1993
1994     SetThreadPoolAllocator(pool);
1995
1996     for (int s = 0; s < EShLangCount; ++s) {
1997         if (! linkStage((EShLanguage)s, messages))
1998             error = true;
1999     }
2000
2001     if (!error) {
2002         if (! crossStageCheck(messages))
2003             error = true;
2004     }
2005
2006     return ! error;
2007 }
2008
2009 //
2010 // Merge the compilation units within the given stage into a single TIntermediate.
2011 //
2012 // Return true for success.
2013 //
2014 bool TProgram::linkStage(EShLanguage stage, EShMessages messages)
2015 {
2016     if (stages[stage].size() == 0)
2017         return true;
2018
2019 #if !defined(GLSLANG_WEB) && !defined(GLSLANG_ANGLE)
2020     int numEsShaders = 0, numNonEsShaders = 0;
2021     for (auto it = stages[stage].begin(); it != stages[stage].end(); ++it) {
2022         if ((*it)->intermediate->getProfile() == EEsProfile) {
2023             numEsShaders++;
2024         } else {
2025             numNonEsShaders++;
2026         }
2027     }
2028
2029     if (numEsShaders > 0 && numNonEsShaders > 0) {
2030         infoSink->info.message(EPrefixError, "Cannot mix ES profile with non-ES profile shaders");
2031         return false;
2032     } else if (numEsShaders > 1) {
2033         infoSink->info.message(EPrefixError, "Cannot attach multiple ES shaders of the same type to a single program");
2034         return false;
2035     }
2036
2037     //
2038     // Be efficient for the common single compilation unit per stage case,
2039     // reusing it's TIntermediate instead of merging into a new one.
2040     //
2041     TIntermediate *firstIntermediate = stages[stage].front()->intermediate;
2042     if (stages[stage].size() == 1)
2043         intermediate[stage] = firstIntermediate;
2044     else {
2045         intermediate[stage] = new TIntermediate(stage,
2046                                                 firstIntermediate->getVersion(),
2047                                                 firstIntermediate->getProfile());
2048         intermediate[stage]->setLimits(firstIntermediate->getLimits());
2049
2050         // The new TIntermediate must use the same origin as the original TIntermediates.
2051         // Otherwise linking will fail due to different coordinate systems.
2052         if (firstIntermediate->getOriginUpperLeft()) {
2053             intermediate[stage]->setOriginUpperLeft();
2054         }
2055         intermediate[stage]->setSpv(firstIntermediate->getSpv());
2056
2057         newedIntermediate[stage] = true;
2058     }
2059
2060     if (messages & EShMsgAST)
2061         infoSink->info << "\nLinked " << StageName(stage) << " stage:\n\n";
2062
2063     if (stages[stage].size() > 1) {
2064         std::list<TShader*>::const_iterator it;
2065         for (it = stages[stage].begin(); it != stages[stage].end(); ++it)
2066             intermediate[stage]->merge(*infoSink, *(*it)->intermediate);
2067     }
2068 #else
2069     intermediate[stage] = stages[stage].front()->intermediate;
2070 #endif
2071     intermediate[stage]->finalCheck(*infoSink, (messages & EShMsgKeepUncalled) != 0);
2072
2073 #ifndef GLSLANG_ANGLE
2074     if (messages & EShMsgAST)
2075         intermediate[stage]->output(*infoSink, true);
2076 #endif
2077
2078     return intermediate[stage]->getNumErrors() == 0;
2079 }
2080
2081 //
2082 // Check that there are no errors in linker objects accross stages
2083 //
2084 // Return true if no errors.
2085 //
2086 bool TProgram::crossStageCheck(EShMessages) {
2087
2088     // make temporary intermediates to hold the linkage symbols for each linking interface
2089     // while we do the checks
2090     // Independent interfaces are:
2091     //                  all uniform variables and blocks
2092     //                  all buffer blocks
2093     //                  all in/out on a stage boundary
2094
2095     TVector<TIntermediate*> activeStages;
2096     for (int s = 0; s < EShLangCount; ++s) {
2097         if (intermediate[s])
2098             activeStages.push_back(intermediate[s]);
2099     }
2100
2101     // no extra linking if there is only one stage
2102     if (! (activeStages.size() > 1))
2103         return true;
2104
2105     // setup temporary tree to hold unfirom objects from different stages
2106     TIntermediate* firstIntermediate = activeStages.front();
2107     TIntermediate uniforms(EShLangCount,
2108                            firstIntermediate->getVersion(),
2109                            firstIntermediate->getProfile());
2110     uniforms.setSpv(firstIntermediate->getSpv());
2111
2112     TIntermAggregate uniformObjects(EOpLinkerObjects);
2113     TIntermAggregate root(EOpSequence);
2114     root.getSequence().push_back(&uniformObjects);
2115     uniforms.setTreeRoot(&root);
2116
2117     bool error = false;
2118
2119     // merge uniforms from all stages into a single intermediate
2120     for (unsigned int i = 0; i < activeStages.size(); ++i) {
2121         uniforms.mergeUniformObjects(*infoSink, *activeStages[i]);
2122     }
2123     error |= uniforms.getNumErrors() != 0;
2124
2125     // copy final definition of global block back into each stage
2126     for (unsigned int i = 0; i < activeStages.size(); ++i) {
2127         // We only want to merge into already existing global uniform blocks.
2128         // A stage that doesn't already know about the global doesn't care about it's content.
2129         // Otherwise we end up pointing to the same object between different stages
2130         // and that will break binding/set remappings
2131         bool mergeExistingOnly = true;
2132         activeStages[i]->mergeGlobalUniformBlocks(*infoSink, uniforms, mergeExistingOnly);
2133     }
2134
2135     // compare cross stage symbols for each stage boundary
2136     for (unsigned int i = 1; i < activeStages.size(); ++i) {
2137         activeStages[i - 1]->checkStageIO(*infoSink, *activeStages[i]);
2138         error |= (activeStages[i - 1]->getNumErrors() != 0);
2139     }
2140
2141     return !error;
2142 }
2143
2144 const char* TProgram::getInfoLog()
2145 {
2146     return infoSink->info.c_str();
2147 }
2148
2149 const char* TProgram::getInfoDebugLog()
2150 {
2151     return infoSink->debug.c_str();
2152 }
2153
2154 #if !defined(GLSLANG_WEB) && !defined(GLSLANG_ANGLE)
2155
2156 //
2157 // Reflection implementation.
2158 //
2159
2160 bool TProgram::buildReflection(int opts)
2161 {
2162     if (! linked || reflection != nullptr)
2163         return false;
2164
2165     int firstStage = EShLangVertex, lastStage = EShLangFragment;
2166
2167     if (opts & EShReflectionIntermediateIO) {
2168         // if we're reflecting intermediate I/O, determine the first and last stage linked and use those as the
2169         // boundaries for which stages generate pipeline inputs/outputs
2170         firstStage = EShLangCount;
2171         lastStage = 0;
2172         for (int s = 0; s < EShLangCount; ++s) {
2173             if (intermediate[s]) {
2174                 firstStage = std::min(firstStage, s);
2175                 lastStage = std::max(lastStage, s);
2176             }
2177         }
2178     }
2179
2180     reflection = new TReflection((EShReflectionOptions)opts, (EShLanguage)firstStage, (EShLanguage)lastStage);
2181
2182     for (int s = 0; s < EShLangCount; ++s) {
2183         if (intermediate[s]) {
2184             if (! reflection->addStage((EShLanguage)s, *intermediate[s]))
2185                 return false;
2186         }
2187     }
2188
2189     return true;
2190 }
2191
2192 unsigned TProgram::getLocalSize(int dim) const                        { return reflection->getLocalSize(dim); }
2193 int TProgram::getReflectionIndex(const char* name) const              { return reflection->getIndex(name); }
2194 int TProgram::getReflectionPipeIOIndex(const char* name, const bool inOrOut) const
2195                                                                       { return reflection->getPipeIOIndex(name, inOrOut); }
2196
2197 int TProgram::getNumUniformVariables() const                          { return reflection->getNumUniforms(); }
2198 const TObjectReflection& TProgram::getUniform(int index) const        { return reflection->getUniform(index); }
2199 int TProgram::getNumUniformBlocks() const                             { return reflection->getNumUniformBlocks(); }
2200 const TObjectReflection& TProgram::getUniformBlock(int index) const   { return reflection->getUniformBlock(index); }
2201 int TProgram::getNumPipeInputs() const                                { return reflection->getNumPipeInputs(); }
2202 const TObjectReflection& TProgram::getPipeInput(int index) const      { return reflection->getPipeInput(index); }
2203 int TProgram::getNumPipeOutputs() const                               { return reflection->getNumPipeOutputs(); }
2204 const TObjectReflection& TProgram::getPipeOutput(int index) const     { return reflection->getPipeOutput(index); }
2205 int TProgram::getNumBufferVariables() const                           { return reflection->getNumBufferVariables(); }
2206 const TObjectReflection& TProgram::getBufferVariable(int index) const { return reflection->getBufferVariable(index); }
2207 int TProgram::getNumBufferBlocks() const                              { return reflection->getNumStorageBuffers(); }
2208 const TObjectReflection& TProgram::getBufferBlock(int index) const    { return reflection->getStorageBufferBlock(index); }
2209 int TProgram::getNumAtomicCounters() const                            { return reflection->getNumAtomicCounters(); }
2210 const TObjectReflection& TProgram::getAtomicCounter(int index) const  { return reflection->getAtomicCounter(index); }
2211 void TProgram::dumpReflection() { if (reflection != nullptr) reflection->dump(); }
2212
2213 //
2214 // I/O mapping implementation.
2215 //
2216 bool TProgram::mapIO(TIoMapResolver* pResolver, TIoMapper* pIoMapper)
2217 {
2218     if (! linked)
2219         return false;
2220     TIoMapper* ioMapper = nullptr;
2221     TIoMapper defaultIOMapper;
2222     if (pIoMapper == nullptr)
2223         ioMapper = &defaultIOMapper;
2224     else
2225         ioMapper = pIoMapper;
2226     for (int s = 0; s < EShLangCount; ++s) {
2227         if (intermediate[s]) {
2228             if (! ioMapper->addStage((EShLanguage)s, *intermediate[s], *infoSink, pResolver))
2229                 return false;
2230         }
2231     }
2232
2233     return ioMapper->doMap(pResolver, *infoSink);
2234 }
2235
2236 #endif // !GLSLANG_WEB && !GLSLANG_ANGLE
2237
2238 } // end namespace glslang