blob: dc9cfaa6a17915201408960f17251fc9d12157b1 [file] [log] [blame]
alokp@chromium.org07620a52010-09-23 17:53:56 +00001//
Jamie Madill88f6e942014-02-19 10:27:53 -05002// Copyright (c) 2002-2014 The ANGLE Project Authors. All rights reserved.
alokp@chromium.org07620a52010-09-23 17:53:56 +00003// Use of this source code is governed by a BSD-style license that can be
4// found in the LICENSE file.
5//
6
Corentin Wallez8b28a8b2016-09-15 19:47:56 -04007#include "compiler/translator/Compiler.h"
8
9#include <sstream>
10
11#include "angle_gl.h"
12#include "common/utilities.h"
Qiankun Miao09cfac62016-09-06 17:25:16 +080013#include "compiler/translator/AddAndTrueToLoopCondition.h"
Dmitry Skiba01971112015-07-10 14:54:00 -040014#include "compiler/translator/Cache.h"
Corentin Wallez71d147f2015-02-11 11:15:24 -080015#include "compiler/translator/CallDAG.h"
Olli Etuaho3d932d82016-04-12 11:10:30 +030016#include "compiler/translator/DeferGlobalInitializers.h"
Zhenyao Mo4e94fea2016-08-09 14:31:37 -070017#include "compiler/translator/EmulateGLFragColorBroadcast.h"
Jamie Madilld5696192016-10-06 11:09:24 -040018#include "compiler/translator/EmulatePrecision.h"
Geoff Lang17732822013-08-29 13:46:49 -040019#include "compiler/translator/Initialize.h"
Geoff Lang17732822013-08-29 13:46:49 -040020#include "compiler/translator/InitializeParseContext.h"
Zhenyao Mo4a667fe2014-02-11 12:35:01 -080021#include "compiler/translator/InitializeVariables.h"
Jamie Madill6b9cb252013-10-17 10:45:47 -040022#include "compiler/translator/ParseContext.h"
Olli Etuahoc6833112015-04-22 15:15:54 +030023#include "compiler/translator/PruneEmptyDeclarations.h"
Zhenyao Moe740add2014-07-18 17:01:01 -070024#include "compiler/translator/RegenerateStructNames.h"
Qiankun Miao705a9192016-08-29 10:05:27 +080025#include "compiler/translator/RemoveInvariantDeclaration.h"
Olli Etuaho5c407bb2015-06-01 12:20:39 +030026#include "compiler/translator/RemovePow.h"
Corentin Wallezd4b50542015-09-28 12:19:26 -070027#include "compiler/translator/RewriteDoWhile.h"
Zhenyao Mocd68fe72014-07-11 10:45:44 -070028#include "compiler/translator/ScalarizeVecAndMatConstructorArgs.h"
Zhenyao Mo7cab38b2013-10-15 12:59:30 -070029#include "compiler/translator/UnfoldShortCircuitAST.h"
Qin Jiajia7835b522016-10-08 11:20:17 +080030#include "compiler/translator/UseInterfaceBlockFields.h"
Geoff Lang17732822013-08-29 13:46:49 -040031#include "compiler/translator/ValidateLimitations.h"
Olli Etuaho19d1dc92016-03-08 17:18:46 +020032#include "compiler/translator/ValidateMaxParameters.h"
Geoff Lang17732822013-08-29 13:46:49 -040033#include "compiler/translator/ValidateOutputs.h"
34#include "compiler/translator/VariablePacker.h"
shannon.woods@transgaming.comda1ed362013-01-25 21:54:57 +000035#include "third_party/compiler/ArrayBoundsClamper.h"
Corentin Wallez28b65282016-06-16 07:24:50 -070036
Jamie Madillacb4b812016-11-07 13:50:29 -050037namespace sh
38{
39
Corentin Wallez28b65282016-06-16 07:24:50 -070040namespace
41{
42
43#if defined(ANGLE_ENABLE_FUZZER_CORPUS_OUTPUT)
44void DumpFuzzerCase(char const *const *shaderStrings,
45 size_t numStrings,
46 uint32_t type,
47 uint32_t spec,
48 uint32_t output,
49 uint64_t options)
50{
51 static int fileIndex = 0;
52
53 std::ostringstream o;
54 o << "corpus/" << fileIndex++ << ".sample";
55 std::string s = o.str();
56
57 // Must match the input format of the fuzzer
58 FILE *f = fopen(s.c_str(), "w");
59 fwrite(&type, sizeof(type), 1, f);
60 fwrite(&spec, sizeof(spec), 1, f);
61 fwrite(&output, sizeof(output), 1, f);
62 fwrite(&options, sizeof(options), 1, f);
63
64 char zero[128 - 20] = {0};
65 fwrite(&zero, 128 - 20, 1, f);
66
67 for (size_t i = 0; i < numStrings; i++)
68 {
69 fwrite(shaderStrings[i], sizeof(char), strlen(shaderStrings[i]), f);
70 }
71 fwrite(&zero, 1, 1, f);
72
73 fclose(f);
74}
75#endif // defined(ANGLE_ENABLE_FUZZER_CORPUS_OUTPUT)
76} // anonymous namespace
77
Jamie Madill5508f392014-02-20 13:31:36 -050078bool IsWebGLBasedSpec(ShShaderSpec spec)
maxvujovic@gmail.com430f5e02012-06-08 17:47:59 +000079{
Qiankun Miaoc2c5fc42016-08-31 15:24:22 +080080 return (spec == SH_WEBGL_SPEC || spec == SH_WEBGL2_SPEC || spec == SH_WEBGL3_SPEC);
maxvujovic@gmail.com430f5e02012-06-08 17:47:59 +000081}
82
Qingqing Dengad0d0792015-04-08 14:25:06 -070083bool IsGLSL130OrNewer(ShShaderOutput output)
84{
Jamie Madillacb4b812016-11-07 13:50:29 -050085 return (output == SH_GLSL_130_OUTPUT || output == SH_GLSL_140_OUTPUT ||
86 output == SH_GLSL_150_CORE_OUTPUT || output == SH_GLSL_330_CORE_OUTPUT ||
87 output == SH_GLSL_400_CORE_OUTPUT || output == SH_GLSL_410_CORE_OUTPUT ||
88 output == SH_GLSL_420_CORE_OUTPUT || output == SH_GLSL_430_CORE_OUTPUT ||
89 output == SH_GLSL_440_CORE_OUTPUT || output == SH_GLSL_450_CORE_OUTPUT);
Qingqing Dengad0d0792015-04-08 14:25:06 -070090}
91
Qiankun Miao705a9192016-08-29 10:05:27 +080092bool IsGLSL420OrNewer(ShShaderOutput output)
93{
Jamie Madillacb4b812016-11-07 13:50:29 -050094 return (output == SH_GLSL_420_CORE_OUTPUT || output == SH_GLSL_430_CORE_OUTPUT ||
95 output == SH_GLSL_440_CORE_OUTPUT || output == SH_GLSL_450_CORE_OUTPUT);
Qiankun Miao705a9192016-08-29 10:05:27 +080096}
97
Zhenyao Mob7bf7422016-11-08 14:44:05 -080098bool IsGLSL410OrOlder(ShShaderOutput output)
99{
100 return (output == SH_GLSL_130_OUTPUT || output == SH_GLSL_140_OUTPUT ||
101 output == SH_GLSL_150_CORE_OUTPUT || output == SH_GLSL_330_CORE_OUTPUT ||
102 output == SH_GLSL_400_CORE_OUTPUT || output == SH_GLSL_410_CORE_OUTPUT);
103}
104
Qiankun Miao89dd8f32016-11-09 12:59:30 +0000105bool RemoveInvariant(sh::GLenum shaderType,
106 int shaderVersion,
107 ShShaderOutput outputType,
108 ShCompileOptions compileOptions)
109{
110 if ((compileOptions & SH_DONT_REMOVE_INVARIANT_FOR_FRAGMENT_INPUT) == 0 &&
111 shaderType == GL_FRAGMENT_SHADER && IsGLSL420OrNewer(outputType))
112 return true;
113
114 if ((compileOptions & SH_REMOVE_INVARIANT_AND_CENTROID_FOR_ESSL3) != 0 &&
Qiankun Miao41f9f672016-11-16 17:04:36 +0800115 shaderVersion >= 300 && shaderType == GL_VERTEX_SHADER)
Qiankun Miao89dd8f32016-11-09 12:59:30 +0000116 return true;
117
118 return false;
119}
120
Zhenyao Mo7faf1a12014-04-25 18:03:56 -0700121size_t GetGlobalMaxTokenSize(ShShaderSpec spec)
Jamie Madill88f6e942014-02-19 10:27:53 -0500122{
He Yunchao29ab9ff2015-08-06 16:58:30 +0800123 // WebGL defines a max token length of 256, while ES2 leaves max token
Jamie Madill88f6e942014-02-19 10:27:53 -0500124 // size undefined. ES3 defines a max size of 1024 characters.
Zhenyao Modb9b40b2014-10-29 15:00:04 -0700125 switch (spec)
Jamie Madill88f6e942014-02-19 10:27:53 -0500126 {
Jamie Madillacb4b812016-11-07 13:50:29 -0500127 case SH_WEBGL_SPEC:
128 return 256;
129 default:
130 return 1024;
Jamie Madill88f6e942014-02-19 10:27:53 -0500131 }
132}
133
Jamie Madilld7b1ab52016-12-12 14:42:19 -0500134namespace
135{
Zhenyao Modb9b40b2014-10-29 15:00:04 -0700136
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800137class TScopedPoolAllocator
138{
139 public:
Jamie Madilld7b1ab52016-12-12 14:42:19 -0500140 TScopedPoolAllocator(TPoolAllocator *allocator) : mAllocator(allocator)
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800141 {
Alok Priyadarshibc3f1ac2013-09-23 14:57:02 -0400142 mAllocator->push();
alokp@chromium.orgbafcbaa2010-11-23 19:07:43 +0000143 SetGlobalPoolAllocator(mAllocator);
144 }
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800145 ~TScopedPoolAllocator()
146 {
alokp@chromium.orgbafcbaa2010-11-23 19:07:43 +0000147 SetGlobalPoolAllocator(NULL);
Alok Priyadarshibc3f1ac2013-09-23 14:57:02 -0400148 mAllocator->pop();
alokp@chromium.orgbafcbaa2010-11-23 19:07:43 +0000149 }
150
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800151 private:
Jamie Madilld7b1ab52016-12-12 14:42:19 -0500152 TPoolAllocator *mAllocator;
Alok Priyadarshibc3f1ac2013-09-23 14:57:02 -0400153};
154
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800155class TScopedSymbolTableLevel
156{
157 public:
Jamie Madilld7b1ab52016-12-12 14:42:19 -0500158 TScopedSymbolTableLevel(TSymbolTable *table) : mTable(table)
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800159 {
Alok Priyadarshibc3f1ac2013-09-23 14:57:02 -0400160 ASSERT(mTable->atBuiltInLevel());
161 mTable->push();
162 }
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800163 ~TScopedSymbolTableLevel()
164 {
Alok Priyadarshibc3f1ac2013-09-23 14:57:02 -0400165 while (!mTable->atBuiltInLevel())
166 mTable->pop();
167 }
168
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800169 private:
Jamie Madilld7b1ab52016-12-12 14:42:19 -0500170 TSymbolTable *mTable;
alokp@chromium.orgbafcbaa2010-11-23 19:07:43 +0000171};
Zhenyao Modb9b40b2014-10-29 15:00:04 -0700172
173int MapSpecToShaderVersion(ShShaderSpec spec)
174{
175 switch (spec)
176 {
Jamie Madillacb4b812016-11-07 13:50:29 -0500177 case SH_GLES2_SPEC:
178 case SH_WEBGL_SPEC:
179 return 100;
180 case SH_GLES3_SPEC:
181 case SH_WEBGL2_SPEC:
182 return 300;
183 case SH_GLES3_1_SPEC:
184 case SH_WEBGL3_SPEC:
185 return 310;
186 default:
187 UNREACHABLE();
188 return 0;
Zhenyao Modb9b40b2014-10-29 15:00:04 -0700189 }
190}
191
alokp@chromium.orgbafcbaa2010-11-23 19:07:43 +0000192} // namespace
193
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800194TShHandleBase::TShHandleBase()
195{
alokp@chromium.orgbafcbaa2010-11-23 19:07:43 +0000196 allocator.push();
197 SetGlobalPoolAllocator(&allocator);
198}
199
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800200TShHandleBase::~TShHandleBase()
201{
alokp@chromium.orgbafcbaa2010-11-23 19:07:43 +0000202 SetGlobalPoolAllocator(NULL);
203 allocator.popAll();
204}
205
Jamie Madill183bde52014-07-02 15:31:19 -0400206TCompiler::TCompiler(sh::GLenum type, ShShaderSpec spec, ShShaderOutput output)
Kenneth Russellbccc65d2016-07-19 16:48:43 -0700207 : variablesCollected(false),
208 shaderType(type),
zmo@google.comf420c422011-09-12 18:27:59 +0000209 shaderSpec(spec),
Jamie Madill68fe74a2014-05-27 12:56:01 -0400210 outputType(output),
Jamie Madilleb1a0102013-07-08 13:31:38 -0400211 maxUniformVectors(0),
212 maxExpressionComplexity(0),
213 maxCallStackDepth(0),
Olli Etuaho19d1dc92016-03-08 17:18:46 +0200214 maxFunctionParameters(0),
shannon.woods%transgaming.com@gtempaccount.comcbb6b6a2013-04-13 03:27:47 +0000215 fragmentPrecisionHigh(false),
shannon.woods@transgaming.com1d432bb2013-01-25 21:57:28 +0000216 clampingStrategy(SH_CLAMP_WITH_CLAMP_INTRINSIC),
Olli Etuaho8efc5ad2015-03-03 17:21:10 +0200217 builtInFunctionEmulator(),
Corentin Wallezd4b50542015-09-28 12:19:26 -0700218 mSourcePath(NULL),
Martin Radev802abe02016-08-04 17:48:32 +0300219 mComputeShaderLocalSizeDeclared(false),
Corentin Wallezd4b50542015-09-28 12:19:26 -0700220 mTemporaryIndex(0)
alokp@chromium.org4888ceb2010-10-01 21:13:12 +0000221{
Martin Radev802abe02016-08-04 17:48:32 +0300222 mComputeShaderLocalSize.fill(1);
alokp@chromium.org4888ceb2010-10-01 21:13:12 +0000223}
224
225TCompiler::~TCompiler()
226{
227}
228
Qiankun Miao7ebb97f2016-09-08 18:01:50 +0800229bool TCompiler::shouldRunLoopAndIndexingValidation(ShCompileOptions compileOptions) const
Olli Etuaho5d91dda2015-06-18 15:47:46 +0300230{
231 // If compiling an ESSL 1.00 shader for WebGL, or if its been requested through the API,
232 // validate loop and indexing as well (to verify that the shader only uses minimal functionality
233 // of ESSL 1.00 as in Appendix A of the spec).
234 return (IsWebGLBasedSpec(shaderSpec) && shaderVersion == 100) ||
235 (compileOptions & SH_VALIDATE_LOOP_INDEXING);
236}
237
Jamie Madilld7b1ab52016-12-12 14:42:19 -0500238bool TCompiler::Init(const ShBuiltInResources &resources)
alokp@chromium.org07620a52010-09-23 17:53:56 +0000239{
Jamie Madilld7b1ab52016-12-12 14:42:19 -0500240 shaderVersion = 100;
241 maxUniformVectors = (shaderType == GL_VERTEX_SHADER) ? resources.MaxVertexUniformVectors
242 : resources.MaxFragmentUniformVectors;
Jamie Madilleb1a0102013-07-08 13:31:38 -0400243 maxExpressionComplexity = resources.MaxExpressionComplexity;
Olli Etuaho19d1dc92016-03-08 17:18:46 +0200244 maxCallStackDepth = resources.MaxCallStackDepth;
245 maxFunctionParameters = resources.MaxFunctionParameters;
Alok Priyadarshibc3f1ac2013-09-23 14:57:02 -0400246
247 SetGlobalPoolAllocator(&allocator);
alokp@chromium.orgbafcbaa2010-11-23 19:07:43 +0000248
alokp@chromium.org07620a52010-09-23 17:53:56 +0000249 // Generate built-in symbol table.
250 if (!InitBuiltInSymbolTable(resources))
251 return false;
alokp@chromium.org07620a52010-09-23 17:53:56 +0000252 InitExtensionBehavior(resources, extensionBehavior);
shannon.woods%transgaming.com@gtempaccount.comcbb6b6a2013-04-13 03:27:47 +0000253 fragmentPrecisionHigh = resources.FragmentPrecisionHigh == 1;
alokp@chromium.orgbafcbaa2010-11-23 19:07:43 +0000254
shannon.woods@transgaming.com1d432bb2013-01-25 21:57:28 +0000255 arrayBoundsClamper.SetClampingStrategy(resources.ArrayIndexClampingStrategy);
256 clampingStrategy = resources.ArrayIndexClampingStrategy;
257
daniel@transgaming.comc23f4612012-11-28 19:42:57 +0000258 hashFunction = resources.HashFunction;
259
alokp@chromium.org07620a52010-09-23 17:53:56 +0000260 return true;
261}
262
Olli Etuaho6d40bbd2016-09-30 13:49:38 +0100263TIntermBlock *TCompiler::compileTreeForTesting(const char *const shaderStrings[],
264 size_t numStrings,
265 ShCompileOptions compileOptions)
alokp@chromium.org07620a52010-09-23 17:53:56 +0000266{
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200267 return compileTreeImpl(shaderStrings, numStrings, compileOptions);
268}
269
Olli Etuaho6d40bbd2016-09-30 13:49:38 +0100270TIntermBlock *TCompiler::compileTreeImpl(const char *const shaderStrings[],
271 size_t numStrings,
272 const ShCompileOptions compileOptions)
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200273{
alokp@chromium.org07620a52010-09-23 17:53:56 +0000274 clearResults();
275
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200276 ASSERT(numStrings > 0);
277 ASSERT(GetGlobalPoolAllocator());
alokp@chromium.org07620a52010-09-23 17:53:56 +0000278
David Yen0fbd1282015-02-02 14:46:09 -0800279 // Reset the extension behavior for each compilation unit.
280 ResetExtensionBehavior(extensionBehavior);
281
apatrick@chromium.org0f4cefe2011-01-26 19:30:57 +0000282 // First string is path of source file if flag is set. The actual source follows.
shannon.woods@transgaming.comd64b3da2013-02-28 23:19:26 +0000283 size_t firstSource = 0;
apatrick@chromium.org0f4cefe2011-01-26 19:30:57 +0000284 if (compileOptions & SH_SOURCE_PATH)
285 {
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200286 mSourcePath = shaderStrings[0];
apatrick@chromium.org0f4cefe2011-01-26 19:30:57 +0000287 ++firstSource;
288 }
289
Olli Etuahof119a262016-08-19 15:54:22 +0300290 TParseContext parseContext(symbolTable, extensionBehavior, shaderType, shaderSpec,
Olli Etuahoe1a94c62015-11-16 17:35:25 +0200291 compileOptions, true, infoSink, getResources());
Olli Etuaho853dc1a2014-11-06 17:25:48 +0200292
Olli Etuahoa6996682015-10-12 14:32:30 +0300293 parseContext.setFragmentPrecisionHighOnESSL1(fragmentPrecisionHigh);
Alok Priyadarshi8156b6b2013-09-23 14:56:58 -0400294 SetGlobalParseContext(&parseContext);
alokp@chromium.org07620a52010-09-23 17:53:56 +0000295
296 // We preserve symbols at the built-in level from compile-to-compile.
297 // Start pushing the user-defined symbols at global level.
Alok Priyadarshibc3f1ac2013-09-23 14:57:02 -0400298 TScopedSymbolTableLevel scopedSymbolLevel(&symbolTable);
alokp@chromium.org07620a52010-09-23 17:53:56 +0000299
300 // Parse shader.
Jamie Madilld7b1ab52016-12-12 14:42:19 -0500301 bool success = (PaParseStrings(numStrings - firstSource, &shaderStrings[firstSource], nullptr,
302 &parseContext) == 0) &&
303 (parseContext.getTreeRoot() != nullptr);
shannon.woods%transgaming.com@gtempaccount.com0bbed382013-04-13 03:38:07 +0000304
shannon.woods%transgaming.com@gtempaccount.com5524db02013-04-13 03:38:16 +0000305 shaderVersion = parseContext.getShaderVersion();
Zhenyao Modb9b40b2014-10-29 15:00:04 -0700306 if (success && MapSpecToShaderVersion(shaderSpec) < shaderVersion)
307 {
308 infoSink.info.prefix(EPrefixError);
309 infoSink.info << "unsupported shader version";
310 success = false;
311 }
shannon.woods%transgaming.com@gtempaccount.com0bbed382013-04-13 03:38:07 +0000312
Olli Etuaho6d40bbd2016-09-30 13:49:38 +0100313 TIntermBlock *root = nullptr;
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200314
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800315 if (success)
316 {
Zhenyao Mo94ac7b72014-10-15 18:22:08 -0700317 mPragma = parseContext.pragma();
Kenneth Russell8bad46d2016-07-01 19:52:52 -0700318 symbolTable.setGlobalInvariant(mPragma.stdgl.invariantAll);
Zhenyao Mo94ac7b72014-10-15 18:22:08 -0700319
Martin Radev802abe02016-08-04 17:48:32 +0300320 mComputeShaderLocalSizeDeclared = parseContext.isComputeShaderLocalSizeDeclared();
321 mComputeShaderLocalSize = parseContext.getComputeShaderLocalSize();
322
Jamie Madill6e06b1f2015-05-14 10:01:17 -0400323 root = parseContext.getTreeRoot();
alokp@chromium.orgb59a7782010-11-24 18:38:33 +0000324
Olli Etuahoa6996682015-10-12 14:32:30 +0300325 // Highp might have been auto-enabled based on shader version
326 fragmentPrecisionHigh = parseContext.getFragmentPrecisionHigh();
327
Jamie Madill6654bc92014-03-26 14:01:57 -0400328 // Disallow expressions deemed too complex.
329 if (success && (compileOptions & SH_LIMIT_EXPRESSION_COMPLEXITY))
330 success = limitExpressionComplexity(root);
331
Corentin Wallez71d147f2015-02-11 11:15:24 -0800332 // Create the function DAG and check there is no recursion
zmo@google.comb1762df2011-07-30 02:04:23 +0000333 if (success)
Corentin Wallez71d147f2015-02-11 11:15:24 -0800334 success = initCallDag(root);
335
336 if (success && (compileOptions & SH_LIMIT_CALL_STACK_DEPTH))
337 success = checkCallDepth();
338
339 // Checks which functions are used and if "main" exists
340 if (success)
341 {
342 functionMetadata.clear();
343 functionMetadata.resize(mCallDag.size());
344 success = tagUsedFunctions();
345 }
zmo@google.comb1762df2011-07-30 02:04:23 +0000346
Corentin Walleza094a8a2015-04-07 11:53:06 -0700347 if (success && !(compileOptions & SH_DONT_PRUNE_UNUSED_FUNCTIONS))
348 success = pruneUnusedFunctions(root);
349
Jamie Madilld7b1ab52016-12-12 14:42:19 -0500350 // Prune empty declarations to work around driver bugs and to keep declaration output
351 // simple.
Olli Etuahoc6833112015-04-22 15:15:54 +0300352 if (success)
353 PruneEmptyDeclarations(root);
354
Jamie Madill183bde52014-07-02 15:31:19 -0400355 if (success && shaderVersion == 300 && shaderType == GL_FRAGMENT_SHADER)
Jamie Madill05a80ce2013-06-20 11:55:49 -0400356 success = validateOutputs(root);
357
Olli Etuaho5d91dda2015-06-18 15:47:46 +0300358 if (success && shouldRunLoopAndIndexingValidation(compileOptions))
alokp@chromium.orgb59a7782010-11-24 18:38:33 +0000359 success = validateLimitations(root);
alokp@chromium.org07620a52010-09-23 17:53:56 +0000360
Jamie Madilld5696192016-10-06 11:09:24 -0400361 // Fail compilation if precision emulation not supported.
362 if (success && getResources().WEBGL_debug_shader_precision &&
363 getPragma().debugShaderPrecision)
364 {
365 if (!EmulatePrecision::SupportedInLanguage(outputType))
366 {
367 infoSink.info.prefix(EPrefixError);
368 infoSink.info << "Precision emulation not supported for this output type.";
369 success = false;
370 }
371 }
372
zmo@google.com32e97312011-08-24 01:03:11 +0000373 // Built-in function emulation needs to happen after validateLimitations pass.
Olli Etuaho8efc5ad2015-03-03 17:21:10 +0200374 if (success)
375 {
Jamie Madill438dbcf2016-06-17 14:20:05 -0400376 // TODO(jmadill): Remove global pool allocator.
377 GetGlobalPoolAllocator()->lock();
Olli Etuaho8efc5ad2015-03-03 17:21:10 +0200378 initBuiltInFunctionEmulator(&builtInFunctionEmulator, compileOptions);
Jamie Madill438dbcf2016-06-17 14:20:05 -0400379 GetGlobalPoolAllocator()->unlock();
zmo@google.com32e97312011-08-24 01:03:11 +0000380 builtInFunctionEmulator.MarkBuiltInFunctionsForEmulation(root);
Olli Etuaho8efc5ad2015-03-03 17:21:10 +0200381 }
zmo@google.com32e97312011-08-24 01:03:11 +0000382
daniel@transgaming.com4167cc92013-01-11 04:11:53 +0000383 // Clamping uniform array bounds needs to happen after validateLimitations pass.
384 if (success && (compileOptions & SH_CLAMP_INDIRECT_ARRAY_BOUNDS))
385 arrayBoundsClamper.MarkIndirectArrayBoundsForClamping(root);
386
Ian Ewell924b7de2016-01-21 13:54:28 -0500387 // gl_Position is always written in compatibility output mode
388 if (success && shaderType == GL_VERTEX_SHADER &&
389 ((compileOptions & SH_INIT_GL_POSITION) ||
390 (outputType == SH_GLSL_COMPATIBILITY_OUTPUT)))
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800391 initializeGLPosition(root);
Zhenyao Moac44cd22013-09-23 14:57:09 -0400392
Qiankun Miao89dd8f32016-11-09 12:59:30 +0000393 if (success && RemoveInvariant(shaderType, shaderVersion, outputType, compileOptions))
Qiankun Miao705a9192016-08-29 10:05:27 +0800394 sh::RemoveInvariantDeclaration(root);
395
Corentin Wallezd4b50542015-09-28 12:19:26 -0700396 // This pass might emit short circuits so keep it before the short circuit unfolding
397 if (success && (compileOptions & SH_REWRITE_DO_WHILE_LOOPS))
398 RewriteDoWhile(root, getTemporaryIndex());
399
Qiankun Miao09cfac62016-09-06 17:25:16 +0800400 if (success && (compileOptions & SH_ADD_AND_TRUE_TO_LOOP_CONDITION))
401 sh::AddAndTrueToLoopCondition(root);
402
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800403 if (success && (compileOptions & SH_UNFOLD_SHORT_CIRCUIT))
404 {
Zhenyao Mo7cab38b2013-10-15 12:59:30 -0700405 UnfoldShortCircuitAST unfoldShortCircuit;
406 root->traverse(&unfoldShortCircuit);
407 unfoldShortCircuit.updateTree();
408 }
409
Olli Etuaho5c407bb2015-06-01 12:20:39 +0300410 if (success && (compileOptions & SH_REMOVE_POW_WITH_CONSTANT_EXPONENT))
411 {
412 RemovePow(root);
413 }
414
Olli Etuaho4dfe8092015-08-21 17:44:35 +0300415 if (success && shouldCollectVariables(compileOptions))
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800416 {
Zhenyao Mo74da9f22013-09-23 14:57:01 -0400417 collectVariables(root);
Qin Jiajia7835b522016-10-08 11:20:17 +0800418 if (compileOptions & SH_USE_UNUSED_STANDARD_SHARED_BLOCKS)
419 {
420 useAllMembersInUnusedStandardAndSharedBlocks(root);
421 }
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800422 if (compileOptions & SH_ENFORCE_PACKING_RESTRICTIONS)
423 {
gman@chromium.org8d804792012-10-17 21:33:48 +0000424 success = enforcePackingRestrictions();
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800425 if (!success)
426 {
Jamie Madill075edd82013-07-08 13:30:19 -0400427 infoSink.info.prefix(EPrefixError);
428 infoSink.info << "too many uniforms";
gman@chromium.org8d804792012-10-17 21:33:48 +0000429 }
430 }
Zhenyao Mo72111912016-07-20 17:45:56 -0700431 if (success && (compileOptions & SH_INIT_OUTPUT_VARIABLES))
432 {
Olli Etuaho27776e32016-07-22 14:00:56 +0300433 initializeOutputVariables(root);
Zhenyao Mo72111912016-07-20 17:45:56 -0700434 }
gman@chromium.org8d804792012-10-17 21:33:48 +0000435 }
zmo@google.comfd747b82011-04-23 01:30:07 +0000436
Zhenyao Mocd68fe72014-07-11 10:45:44 -0700437 if (success && (compileOptions & SH_SCALARIZE_VEC_AND_MAT_CONSTRUCTOR_ARGS))
438 {
Olli Etuahob990b552016-10-27 12:29:17 +0100439 ScalarizeVecAndMatConstructorArgs(root, shaderType, fragmentPrecisionHigh,
440 &mTemporaryIndex);
Zhenyao Mocd68fe72014-07-11 10:45:44 -0700441 }
442
Zhenyao Moe740add2014-07-18 17:01:01 -0700443 if (success && (compileOptions & SH_REGENERATE_STRUCT_NAMES))
444 {
445 RegenerateStructNames gen(symbolTable, shaderVersion);
446 root->traverse(&gen);
447 }
Olli Etuaho3d932d82016-04-12 11:10:30 +0300448
Zhenyao Mo4e94fea2016-08-09 14:31:37 -0700449 if (success && shaderType == GL_FRAGMENT_SHADER && shaderVersion == 100 &&
450 compileResources.EXT_draw_buffers && compileResources.MaxDrawBuffers > 1 &&
451 IsExtensionEnabled(extensionBehavior, "GL_EXT_draw_buffers"))
452 {
453 EmulateGLFragColorBroadcast(root, compileResources.MaxDrawBuffers, &outputVariables);
454 }
455
Olli Etuaho3d932d82016-04-12 11:10:30 +0300456 if (success)
457 {
458 DeferGlobalInitializers(root);
459 }
alokp@chromium.org07620a52010-09-23 17:53:56 +0000460 }
461
Zhenyao Mo7faf1a12014-04-25 18:03:56 -0700462 SetGlobalParseContext(NULL);
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200463 if (success)
464 return root;
465
466 return NULL;
467}
468
Qiankun Miao7ebb97f2016-09-08 18:01:50 +0800469bool TCompiler::compile(const char *const shaderStrings[],
470 size_t numStrings,
471 ShCompileOptions compileOptionsIn)
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200472{
Corentin Wallez28b65282016-06-16 07:24:50 -0700473#if defined(ANGLE_ENABLE_FUZZER_CORPUS_OUTPUT)
474 DumpFuzzerCase(shaderStrings, numStrings, shaderType, shaderSpec, outputType, compileOptionsIn);
475#endif // defined(ANGLE_ENABLE_FUZZER_CORPUS_OUTPUT)
476
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200477 if (numStrings == 0)
478 return true;
479
Qiankun Miao7ebb97f2016-09-08 18:01:50 +0800480 ShCompileOptions compileOptions = compileOptionsIn;
Kenneth Russellbccc65d2016-07-19 16:48:43 -0700481
482 // Apply key workarounds.
483 if (shouldFlattenPragmaStdglInvariantAll())
484 {
485 // This should be harmless to do in all cases, but for the moment, do it only conditionally.
486 compileOptions |= SH_FLATTEN_PRAGMA_STDGL_INVARIANT_ALL;
487 }
488
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200489 TScopedPoolAllocator scopedAlloc(&allocator);
Olli Etuaho6d40bbd2016-09-30 13:49:38 +0100490 TIntermBlock *root = compileTreeImpl(shaderStrings, numStrings, compileOptions);
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200491
492 if (root)
493 {
494 if (compileOptions & SH_INTERMEDIATE_TREE)
495 TIntermediate::outputTree(root, infoSink.info);
496
497 if (compileOptions & SH_OBJECT_CODE)
498 translate(root, compileOptions);
499
500 // The IntermNode tree doesn't need to be deleted here, since the
501 // memory will be freed in a big chunk by the PoolAllocator.
502 return true;
503 }
504 return false;
alokp@chromium.org07620a52010-09-23 17:53:56 +0000505}
506
Nicolas Capens49a88872013-06-20 09:54:03 -0400507bool TCompiler::InitBuiltInSymbolTable(const ShBuiltInResources &resources)
alokp@chromium.org07620a52010-09-23 17:53:56 +0000508{
Olli Etuaho28cb0362016-11-22 15:42:37 +0000509 if (resources.MaxDrawBuffers < 1)
510 {
511 return false;
512 }
513 if (resources.EXT_blend_func_extended && resources.MaxDualSourceDrawBuffers < 1)
514 {
515 return false;
516 }
517
shannon.woods%transgaming.com@gtempaccount.com18b4c4b2013-04-13 03:31:40 +0000518 compileResources = resources;
Shannon Woods2d76e5f2014-05-16 17:46:41 -0400519 setResourceString();
shannonwoods@chromium.org2ac0be92013-05-30 00:02:27 +0000520
Nicolas Capens49a88872013-06-20 09:54:03 -0400521 assert(symbolTable.isEmpty());
Jamie Madilld7b1ab52016-12-12 14:42:19 -0500522 symbolTable.push(); // COMMON_BUILTINS
523 symbolTable.push(); // ESSL1_BUILTINS
524 symbolTable.push(); // ESSL3_BUILTINS
525 symbolTable.push(); // ESSL3_1_BUILTINS
shannonwoods@chromium.org2ac0be92013-05-30 00:02:27 +0000526
Nicolas Capens49a88872013-06-20 09:54:03 -0400527 TPublicType integer;
Martin Radev2cc85b32016-08-05 16:22:53 +0300528 integer.initializeBasicType(EbtInt);
Nicolas Capens49a88872013-06-20 09:54:03 -0400529
530 TPublicType floatingPoint;
Martin Radev2cc85b32016-08-05 16:22:53 +0300531 floatingPoint.initializeBasicType(EbtFloat);
Nicolas Capens49a88872013-06-20 09:54:03 -0400532
Jamie Madillacb4b812016-11-07 13:50:29 -0500533 switch (shaderType)
Nicolas Capens49a88872013-06-20 09:54:03 -0400534 {
Jamie Madillacb4b812016-11-07 13:50:29 -0500535 case GL_FRAGMENT_SHADER:
536 symbolTable.setDefaultPrecision(integer, EbpMedium);
537 break;
538 case GL_VERTEX_SHADER:
539 symbolTable.setDefaultPrecision(integer, EbpHigh);
540 symbolTable.setDefaultPrecision(floatingPoint, EbpHigh);
541 break;
542 case GL_COMPUTE_SHADER:
543 symbolTable.setDefaultPrecision(integer, EbpHigh);
544 symbolTable.setDefaultPrecision(floatingPoint, EbpHigh);
545 break;
546 default:
547 assert(false && "Language not supported");
Nicolas Capens49a88872013-06-20 09:54:03 -0400548 }
Olli Etuaho183d7e22015-11-20 15:59:09 +0200549 // Set defaults for sampler types that have default precision, even those that are
Zhenyao Moa5a1dfc2013-09-23 14:57:03 -0400550 // only available if an extension exists.
Olli Etuaho183d7e22015-11-20 15:59:09 +0200551 // New sampler types in ESSL3 don't have default precision. ESSL1 types do.
552 initSamplerDefaultPrecision(EbtSampler2D);
553 initSamplerDefaultPrecision(EbtSamplerCube);
554 // SamplerExternalOES is specified in the extension to have default precision.
555 initSamplerDefaultPrecision(EbtSamplerExternalOES);
556 // It isn't specified whether Sampler2DRect has default precision.
557 initSamplerDefaultPrecision(EbtSampler2DRect);
Nicolas Capens49a88872013-06-20 09:54:03 -0400558
Jamie Madill1b452142013-07-12 14:51:11 -0400559 InsertBuiltInFunctions(shaderType, shaderSpec, resources, symbolTable);
Nicolas Capens49a88872013-06-20 09:54:03 -0400560
561 IdentifyBuiltIns(shaderType, shaderSpec, resources, symbolTable);
562
563 return true;
alokp@chromium.org07620a52010-09-23 17:53:56 +0000564}
565
Olli Etuaho183d7e22015-11-20 15:59:09 +0200566void TCompiler::initSamplerDefaultPrecision(TBasicType samplerType)
567{
568 ASSERT(samplerType > EbtGuardSamplerBegin && samplerType < EbtGuardSamplerEnd);
569 TPublicType sampler;
Martin Radev2cc85b32016-08-05 16:22:53 +0300570 sampler.initializeBasicType(samplerType);
Olli Etuaho183d7e22015-11-20 15:59:09 +0200571 symbolTable.setDefaultPrecision(sampler, EbpLow);
572}
573
Shannon Woods2d76e5f2014-05-16 17:46:41 -0400574void TCompiler::setResourceString()
575{
576 std::ostringstream strstream;
Geoff Langb66a9092016-05-16 15:59:14 -0400577
578 // clang-format off
Shannon Woods2d76e5f2014-05-16 17:46:41 -0400579 strstream << ":MaxVertexAttribs:" << compileResources.MaxVertexAttribs
Jamie Madillacb4b812016-11-07 13:50:29 -0500580 << ":MaxVertexUniformVectors:" << compileResources.MaxVertexUniformVectors
581 << ":MaxVaryingVectors:" << compileResources.MaxVaryingVectors
582 << ":MaxVertexTextureImageUnits:" << compileResources.MaxVertexTextureImageUnits
583 << ":MaxCombinedTextureImageUnits:" << compileResources.MaxCombinedTextureImageUnits
584 << ":MaxTextureImageUnits:" << compileResources.MaxTextureImageUnits
585 << ":MaxFragmentUniformVectors:" << compileResources.MaxFragmentUniformVectors
586 << ":MaxDrawBuffers:" << compileResources.MaxDrawBuffers
587 << ":OES_standard_derivatives:" << compileResources.OES_standard_derivatives
588 << ":OES_EGL_image_external:" << compileResources.OES_EGL_image_external
589 << ":OES_EGL_image_external_essl3:" << compileResources.OES_EGL_image_external_essl3
590 << ":NV_EGL_stream_consumer_external:" << compileResources.NV_EGL_stream_consumer_external
591 << ":ARB_texture_rectangle:" << compileResources.ARB_texture_rectangle
592 << ":EXT_draw_buffers:" << compileResources.EXT_draw_buffers
593 << ":FragmentPrecisionHigh:" << compileResources.FragmentPrecisionHigh
594 << ":MaxExpressionComplexity:" << compileResources.MaxExpressionComplexity
595 << ":MaxCallStackDepth:" << compileResources.MaxCallStackDepth
596 << ":MaxFunctionParameters:" << compileResources.MaxFunctionParameters
597 << ":EXT_blend_func_extended:" << compileResources.EXT_blend_func_extended
598 << ":EXT_frag_depth:" << compileResources.EXT_frag_depth
599 << ":EXT_shader_texture_lod:" << compileResources.EXT_shader_texture_lod
600 << ":EXT_shader_framebuffer_fetch:" << compileResources.EXT_shader_framebuffer_fetch
601 << ":NV_shader_framebuffer_fetch:" << compileResources.NV_shader_framebuffer_fetch
602 << ":ARM_shader_framebuffer_fetch:" << compileResources.ARM_shader_framebuffer_fetch
603 << ":MaxVertexOutputVectors:" << compileResources.MaxVertexOutputVectors
604 << ":MaxFragmentInputVectors:" << compileResources.MaxFragmentInputVectors
605 << ":MinProgramTexelOffset:" << compileResources.MinProgramTexelOffset
606 << ":MaxProgramTexelOffset:" << compileResources.MaxProgramTexelOffset
607 << ":MaxDualSourceDrawBuffers:" << compileResources.MaxDualSourceDrawBuffers
608 << ":NV_draw_buffers:" << compileResources.NV_draw_buffers
609 << ":WEBGL_debug_shader_precision:" << compileResources.WEBGL_debug_shader_precision
610 << ":MaxImageUnits:" << compileResources.MaxImageUnits
611 << ":MaxVertexImageUniforms:" << compileResources.MaxVertexImageUniforms
612 << ":MaxFragmentImageUniforms:" << compileResources.MaxFragmentImageUniforms
613 << ":MaxComputeImageUniforms:" << compileResources.MaxComputeImageUniforms
614 << ":MaxCombinedImageUniforms:" << compileResources.MaxCombinedImageUniforms
615 << ":MaxCombinedShaderOutputResources:" << compileResources.MaxCombinedShaderOutputResources
616 << ":MaxComputeWorkGroupCountX:" << compileResources.MaxComputeWorkGroupCount[0]
617 << ":MaxComputeWorkGroupCountY:" << compileResources.MaxComputeWorkGroupCount[1]
618 << ":MaxComputeWorkGroupCountZ:" << compileResources.MaxComputeWorkGroupCount[2]
619 << ":MaxComputeWorkGroupSizeX:" << compileResources.MaxComputeWorkGroupSize[0]
620 << ":MaxComputeWorkGroupSizeY:" << compileResources.MaxComputeWorkGroupSize[1]
621 << ":MaxComputeWorkGroupSizeZ:" << compileResources.MaxComputeWorkGroupSize[2]
622 << ":MaxComputeUniformComponents:" << compileResources.MaxComputeUniformComponents
623 << ":MaxComputeTextureImageUnits:" << compileResources.MaxComputeTextureImageUnits
624 << ":MaxComputeAtomicCounters:" << compileResources.MaxComputeAtomicCounters
625 << ":MaxComputeAtomicCounterBuffers:" << compileResources.MaxComputeAtomicCounterBuffers
626 << ":MaxVertexAtomicCounters:" << compileResources.MaxVertexAtomicCounters
627 << ":MaxFragmentAtomicCounters:" << compileResources.MaxFragmentAtomicCounters
628 << ":MaxCombinedAtomicCounters:" << compileResources.MaxCombinedAtomicCounters
629 << ":MaxAtomicCounterBindings:" << compileResources.MaxAtomicCounterBindings
630 << ":MaxVertexAtomicCounterBuffers:" << compileResources.MaxVertexAtomicCounterBuffers
631 << ":MaxFragmentAtomicCounterBuffers:" << compileResources.MaxFragmentAtomicCounterBuffers
632 << ":MaxCombinedAtomicCounterBuffers:" << compileResources.MaxCombinedAtomicCounterBuffers
633 << ":MaxAtomicCounterBufferSize:" << compileResources.MaxAtomicCounterBufferSize;
Geoff Langb66a9092016-05-16 15:59:14 -0400634 // clang-format on
Shannon Woods2d76e5f2014-05-16 17:46:41 -0400635
636 builtInResourcesString = strstream.str();
637}
638
alokp@chromium.org07620a52010-09-23 17:53:56 +0000639void TCompiler::clearResults()
640{
daniel@transgaming.com4167cc92013-01-11 04:11:53 +0000641 arrayBoundsClamper.Cleanup();
alokp@chromium.org07620a52010-09-23 17:53:56 +0000642 infoSink.info.erase();
643 infoSink.obj.erase();
644 infoSink.debug.erase();
645
Jamie Madilled27c722014-07-02 15:31:23 -0400646 attributes.clear();
647 outputVariables.clear();
alokp@chromium.org07620a52010-09-23 17:53:56 +0000648 uniforms.clear();
Jamie Madill23a8a432014-07-09 13:27:42 -0400649 expandedUniforms.clear();
Zhenyao Mod2d340b2013-09-23 14:57:05 -0400650 varyings.clear();
Jamie Madilled27c722014-07-02 15:31:23 -0400651 interfaceBlocks.clear();
Kenneth Russellbccc65d2016-07-19 16:48:43 -0700652 variablesCollected = false;
zmo@google.coma3b4ab42011-09-16 00:53:26 +0000653
654 builtInFunctionEmulator.Cleanup();
daniel@transgaming.com0aa3b5a2012-11-28 19:43:24 +0000655
656 nameMap.clear();
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200657
Jamie Madilld7b1ab52016-12-12 14:42:19 -0500658 mSourcePath = NULL;
Corentin Wallezd4b50542015-09-28 12:19:26 -0700659 mTemporaryIndex = 0;
alokp@chromium.org07620a52010-09-23 17:53:56 +0000660}
661
Corentin Wallez71d147f2015-02-11 11:15:24 -0800662bool TCompiler::initCallDag(TIntermNode *root)
zmo@google.comb1762df2011-07-30 02:04:23 +0000663{
Corentin Wallez71d147f2015-02-11 11:15:24 -0800664 mCallDag.clear();
665
666 switch (mCallDag.init(root, &infoSink.info))
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800667 {
Jamie Madillacb4b812016-11-07 13:50:29 -0500668 case CallDAG::INITDAG_SUCCESS:
669 return true;
670 case CallDAG::INITDAG_RECURSION:
671 infoSink.info.prefix(EPrefixError);
672 infoSink.info << "Function recursion detected";
673 return false;
674 case CallDAG::INITDAG_UNDEFINED:
675 infoSink.info.prefix(EPrefixError);
676 infoSink.info << "Unimplemented function detected";
677 return false;
Corentin Wallez71d147f2015-02-11 11:15:24 -0800678 }
679
680 UNREACHABLE();
681 return true;
682}
683
684bool TCompiler::checkCallDepth()
685{
686 std::vector<int> depths(mCallDag.size());
687
688 for (size_t i = 0; i < mCallDag.size(); i++)
689 {
Jamie Madilld7b1ab52016-12-12 14:42:19 -0500690 int depth = 0;
Corentin Wallez71d147f2015-02-11 11:15:24 -0800691 auto &record = mCallDag.getRecordFromIndex(i);
692
693 for (auto &calleeIndex : record.callees)
694 {
695 depth = std::max(depth, depths[calleeIndex] + 1);
696 }
697
698 depths[i] = depth;
699
700 if (depth >= maxCallStackDepth)
701 {
702 // Trace back the function chain to have a meaningful info log.
703 infoSink.info.prefix(EPrefixError);
704 infoSink.info << "Call stack too deep (larger than " << maxCallStackDepth
705 << ") with the following call chain: " << record.name;
706
Cooper Partin4d61f7e2015-08-12 10:56:50 -0700707 int currentFunction = static_cast<int>(i);
Jamie Madilld7b1ab52016-12-12 14:42:19 -0500708 int currentDepth = depth;
Corentin Wallez71d147f2015-02-11 11:15:24 -0800709
710 while (currentFunction != -1)
711 {
712 infoSink.info << " -> " << mCallDag.getRecordFromIndex(currentFunction).name;
713
714 int nextFunction = -1;
Jamie Madilld7b1ab52016-12-12 14:42:19 -0500715 for (auto &calleeIndex : mCallDag.getRecordFromIndex(currentFunction).callees)
Corentin Wallez71d147f2015-02-11 11:15:24 -0800716 {
717 if (depths[calleeIndex] == currentDepth - 1)
718 {
719 currentDepth--;
720 nextFunction = calleeIndex;
721 }
722 }
723
724 currentFunction = nextFunction;
725 }
726
727 return false;
728 }
729 }
730
731 return true;
732}
733
734bool TCompiler::tagUsedFunctions()
735{
736 // Search from main, starting from the end of the DAG as it usually is the root.
Cooper Partin4d61f7e2015-08-12 10:56:50 -0700737 for (size_t i = mCallDag.size(); i-- > 0;)
Corentin Wallez71d147f2015-02-11 11:15:24 -0800738 {
739 if (mCallDag.getRecordFromIndex(i).name == "main(")
740 {
741 internalTagUsedFunction(i);
742 return true;
743 }
744 }
745
746 infoSink.info.prefix(EPrefixError);
Olli Etuaho792a41d2015-12-15 12:39:16 +0200747 infoSink.info << "Missing main()\n";
Corentin Wallez71d147f2015-02-11 11:15:24 -0800748 return false;
749}
750
751void TCompiler::internalTagUsedFunction(size_t index)
752{
753 if (functionMetadata[index].used)
754 {
755 return;
756 }
757
758 functionMetadata[index].used = true;
759
760 for (int calleeIndex : mCallDag.getRecordFromIndex(index).callees)
761 {
762 internalTagUsedFunction(calleeIndex);
zmo@google.comb1762df2011-07-30 02:04:23 +0000763 }
764}
765
Corentin Walleza094a8a2015-04-07 11:53:06 -0700766// A predicate for the stl that returns if a top-level node is unused
767class TCompiler::UnusedPredicate
768{
769 public:
770 UnusedPredicate(const CallDAG *callDag, const std::vector<FunctionMetadata> *metadatas)
Jamie Madillacb4b812016-11-07 13:50:29 -0500771 : mCallDag(callDag), mMetadatas(metadatas)
Corentin Walleza094a8a2015-04-07 11:53:06 -0700772 {
773 }
774
Jamie Madilld7b1ab52016-12-12 14:42:19 -0500775 bool operator()(TIntermNode *node)
Corentin Walleza094a8a2015-04-07 11:53:06 -0700776 {
Jamie Madilld7b1ab52016-12-12 14:42:19 -0500777 const TIntermAggregate *asAggregate = node->getAsAggregate();
Olli Etuaho336b1472016-10-05 16:37:55 +0100778 const TIntermFunctionDefinition *asFunction = node->getAsFunctionDefinition();
Corentin Walleza094a8a2015-04-07 11:53:06 -0700779
Olli Etuaho336b1472016-10-05 16:37:55 +0100780 const TFunctionSymbolInfo *functionInfo = nullptr;
781
782 if (asFunction)
783 {
784 functionInfo = asFunction->getFunctionSymbolInfo();
785 }
786 else if (asAggregate)
787 {
788 if (asAggregate->getOp() == EOpPrototype)
789 {
790 functionInfo = asAggregate->getFunctionSymbolInfo();
791 }
792 }
793 if (functionInfo == nullptr)
Corentin Walleza094a8a2015-04-07 11:53:06 -0700794 {
795 return false;
796 }
797
Olli Etuaho336b1472016-10-05 16:37:55 +0100798 size_t callDagIndex = mCallDag->findIndex(functionInfo);
Corentin Walleza094a8a2015-04-07 11:53:06 -0700799 if (callDagIndex == CallDAG::InvalidIndex)
800 {
801 // This happens only for unimplemented prototypes which are thus unused
Olli Etuaho336b1472016-10-05 16:37:55 +0100802 ASSERT(asAggregate && asAggregate->getOp() == EOpPrototype);
Corentin Walleza094a8a2015-04-07 11:53:06 -0700803 return true;
804 }
805
806 ASSERT(callDagIndex < mMetadatas->size());
807 return !(*mMetadatas)[callDagIndex].used;
808 }
809
810 private:
811 const CallDAG *mCallDag;
812 const std::vector<FunctionMetadata> *mMetadatas;
813};
814
Olli Etuaho6d40bbd2016-09-30 13:49:38 +0100815bool TCompiler::pruneUnusedFunctions(TIntermBlock *root)
Corentin Walleza094a8a2015-04-07 11:53:06 -0700816{
Corentin Walleza094a8a2015-04-07 11:53:06 -0700817 UnusedPredicate isUnused(&mCallDag, &functionMetadata);
Olli Etuaho6d40bbd2016-09-30 13:49:38 +0100818 TIntermSequence *sequence = root->getSequence();
Corentin Wallezb081e782015-07-20 05:40:04 -0700819
820 if (!sequence->empty())
821 {
Jamie Madilld7b1ab52016-12-12 14:42:19 -0500822 sequence->erase(std::remove_if(sequence->begin(), sequence->end(), isUnused),
823 sequence->end());
Corentin Wallezb081e782015-07-20 05:40:04 -0700824 }
Corentin Walleza094a8a2015-04-07 11:53:06 -0700825
826 return true;
827}
828
Jamie Madilld7b1ab52016-12-12 14:42:19 -0500829bool TCompiler::validateOutputs(TIntermNode *root)
Jamie Madill05a80ce2013-06-20 11:55:49 -0400830{
Kimmo Kinnunenb18609b2015-07-16 14:13:11 +0300831 ValidateOutputs validateOutputs(getExtensionBehavior(), compileResources.MaxDrawBuffers);
Jamie Madill05a80ce2013-06-20 11:55:49 -0400832 root->traverse(&validateOutputs);
Kimmo Kinnunenb18609b2015-07-16 14:13:11 +0300833 return (validateOutputs.validateAndCountErrors(infoSink.info) == 0);
Jamie Madill05a80ce2013-06-20 11:55:49 -0400834}
835
Jamie Madilld7b1ab52016-12-12 14:42:19 -0500836bool TCompiler::validateLimitations(TIntermNode *root)
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800837{
Olli Etuaho8a76dcc2015-12-10 20:25:12 +0200838 ValidateLimitations validate(shaderType, &infoSink.info);
alokp@chromium.orgb59a7782010-11-24 18:38:33 +0000839 root->traverse(&validate);
840 return validate.numErrors() == 0;
841}
842
Jamie Madilld7b1ab52016-12-12 14:42:19 -0500843bool TCompiler::limitExpressionComplexity(TIntermNode *root)
Jamie Madilleb1a0102013-07-08 13:31:38 -0400844{
Jamie Madillacb4b812016-11-07 13:50:29 -0500845 TMaxDepthTraverser traverser(maxExpressionComplexity + 1);
Jamie Madilleb1a0102013-07-08 13:31:38 -0400846 root->traverse(&traverser);
Jamie Madill6654bc92014-03-26 14:01:57 -0400847
848 if (traverser.getMaxDepth() > maxExpressionComplexity)
849 {
850 infoSink.info << "Expression too complex.";
851 return false;
852 }
853
Olli Etuaho19d1dc92016-03-08 17:18:46 +0200854 if (!ValidateMaxParameters::validate(root, maxFunctionParameters))
855 {
856 infoSink.info << "Function has too many parameters.";
857 return false;
858 }
859
Jamie Madilleb1a0102013-07-08 13:31:38 -0400860 return true;
861}
862
Jamie Madilld7b1ab52016-12-12 14:42:19 -0500863void TCompiler::collectVariables(TIntermNode *root)
alokp@chromium.org07620a52010-09-23 17:53:56 +0000864{
Kenneth Russellbccc65d2016-07-19 16:48:43 -0700865 if (!variablesCollected)
866 {
867 sh::CollectVariables collect(&attributes, &outputVariables, &uniforms, &varyings,
Jamie Madillacb4b812016-11-07 13:50:29 -0500868 &interfaceBlocks, hashFunction, symbolTable,
869 extensionBehavior);
Kenneth Russellbccc65d2016-07-19 16:48:43 -0700870 root->traverse(&collect);
Jamie Madill23a8a432014-07-09 13:27:42 -0400871
Kenneth Russellbccc65d2016-07-19 16:48:43 -0700872 // This is for enforcePackingRestriction().
873 sh::ExpandUniforms(uniforms, &expandedUniforms);
874 variablesCollected = true;
875 }
alokp@chromium.org07620a52010-09-23 17:53:56 +0000876}
zmo@google.comfd747b82011-04-23 01:30:07 +0000877
Corentin Wallez1df16022016-10-27 08:16:56 -0400878bool TCompiler::shouldCollectVariables(ShCompileOptions compileOptions)
879{
880 return (compileOptions & SH_VARIABLES) != 0;
881}
882
883bool TCompiler::wereVariablesCollected() const
884{
885 return variablesCollected;
886}
887
gman@chromium.org8d804792012-10-17 21:33:48 +0000888bool TCompiler::enforcePackingRestrictions()
889{
890 VariablePacker packer;
Jamie Madill23a8a432014-07-09 13:27:42 -0400891 return packer.CheckVariablesWithinPackingLimits(maxUniformVectors, expandedUniforms);
gman@chromium.org8d804792012-10-17 21:33:48 +0000892}
893
Jamie Madilld7b1ab52016-12-12 14:42:19 -0500894void TCompiler::initializeGLPosition(TIntermNode *root)
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800895{
Zhenyao Mo72111912016-07-20 17:45:56 -0700896 InitVariableList list;
897 sh::ShaderVariable var(GL_FLOAT_VEC4, 0);
898 var.name = "gl_Position";
899 list.push_back(var);
Zhenyao Mod7490962016-11-09 15:49:51 -0800900 InitializeVariables(root, list, symbolTable);
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800901}
902
Qin Jiajia7835b522016-10-08 11:20:17 +0800903void TCompiler::useAllMembersInUnusedStandardAndSharedBlocks(TIntermNode *root)
904{
905 sh::InterfaceBlockList list;
906
907 for (auto block : interfaceBlocks)
908 {
909 if (!block.staticUse &&
910 (block.layout == sh::BLOCKLAYOUT_STANDARD || block.layout == sh::BLOCKLAYOUT_SHARED))
911 {
912 list.push_back(block);
913 }
914 }
915
Zhenyao Mod7490962016-11-09 15:49:51 -0800916 sh::UseInterfaceBlockFields(root, list, symbolTable);
Qin Jiajia7835b522016-10-08 11:20:17 +0800917}
918
Olli Etuaho27776e32016-07-22 14:00:56 +0300919void TCompiler::initializeOutputVariables(TIntermNode *root)
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800920{
Zhenyao Mo72111912016-07-20 17:45:56 -0700921 InitVariableList list;
922 if (shaderType == GL_VERTEX_SHADER)
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800923 {
Zhenyao Mo72111912016-07-20 17:45:56 -0700924 for (auto var : varyings)
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800925 {
Zhenyao Mof9312682016-07-22 12:51:31 -0700926 list.push_back(var);
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800927 }
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800928 }
Zhenyao Mo72111912016-07-20 17:45:56 -0700929 else
930 {
931 ASSERT(shaderType == GL_FRAGMENT_SHADER);
932 for (auto var : outputVariables)
933 {
934 list.push_back(var);
935 }
936 }
Zhenyao Mod7490962016-11-09 15:49:51 -0800937 InitializeVariables(root, list, symbolTable);
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800938}
939
Jamie Madilld7b1ab52016-12-12 14:42:19 -0500940const TExtensionBehavior &TCompiler::getExtensionBehavior() const
zmo@google.com5601ea02011-06-10 18:23:25 +0000941{
942 return extensionBehavior;
943}
zmo@google.com32e97312011-08-24 01:03:11 +0000944
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200945const char *TCompiler::getSourcePath() const
946{
947 return mSourcePath;
948}
949
Jamie Madilld7b1ab52016-12-12 14:42:19 -0500950const ShBuiltInResources &TCompiler::getResources() const
shannon.woods%transgaming.com@gtempaccount.com18b4c4b2013-04-13 03:31:40 +0000951{
952 return compileResources;
953}
954
Jamie Madilld7b1ab52016-12-12 14:42:19 -0500955const ArrayBoundsClamper &TCompiler::getArrayBoundsClamper() const
daniel@transgaming.com4167cc92013-01-11 04:11:53 +0000956{
957 return arrayBoundsClamper;
958}
959
shannon.woods@transgaming.com1d432bb2013-01-25 21:57:28 +0000960ShArrayIndexClampingStrategy TCompiler::getArrayIndexClampingStrategy() const
961{
962 return clampingStrategy;
963}
964
Jamie Madilld7b1ab52016-12-12 14:42:19 -0500965const BuiltInFunctionEmulator &TCompiler::getBuiltInFunctionEmulator() const
shannon.woods@transgaming.com1d432bb2013-01-25 21:57:28 +0000966{
967 return builtInFunctionEmulator;
968}
Zhenyao Mo94ac7b72014-10-15 18:22:08 -0700969
Qiankun Miao7ebb97f2016-09-08 18:01:50 +0800970void TCompiler::writePragma(ShCompileOptions compileOptions)
Zhenyao Mo94ac7b72014-10-15 18:22:08 -0700971{
Kenneth Russellbccc65d2016-07-19 16:48:43 -0700972 if (!(compileOptions & SH_FLATTEN_PRAGMA_STDGL_INVARIANT_ALL))
973 {
974 TInfoSinkBase &sink = infoSink.obj;
975 if (mPragma.stdgl.invariantAll)
976 sink << "#pragma STDGL invariant(all)\n";
977 }
978}
979
980bool TCompiler::isVaryingDefined(const char *varyingName)
981{
982 ASSERT(variablesCollected);
983 for (size_t ii = 0; ii < varyings.size(); ++ii)
984 {
985 if (varyings[ii].name == varyingName)
986 {
987 return true;
988 }
989 }
990
991 return false;
Zhenyao Mo94ac7b72014-10-15 18:22:08 -0700992}
Jamie Madillacb4b812016-11-07 13:50:29 -0500993
994} // namespace sh