blob: 7ef30eeb63ed4ae65b34a45ba48a19b46a7d3fe1 [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/ForLoopUnroll.h"
20#include "compiler/translator/Initialize.h"
Geoff Lang17732822013-08-29 13:46:49 -040021#include "compiler/translator/InitializeParseContext.h"
Zhenyao Mo4a667fe2014-02-11 12:35:01 -080022#include "compiler/translator/InitializeVariables.h"
Jamie Madill6b9cb252013-10-17 10:45:47 -040023#include "compiler/translator/ParseContext.h"
Olli Etuahoc6833112015-04-22 15:15:54 +030024#include "compiler/translator/PruneEmptyDeclarations.h"
Zhenyao Moe740add2014-07-18 17:01:01 -070025#include "compiler/translator/RegenerateStructNames.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
37namespace
38{
39
40#if defined(ANGLE_ENABLE_FUZZER_CORPUS_OUTPUT)
41void DumpFuzzerCase(char const *const *shaderStrings,
42 size_t numStrings,
43 uint32_t type,
44 uint32_t spec,
45 uint32_t output,
46 uint64_t options)
47{
48 static int fileIndex = 0;
49
50 std::ostringstream o;
51 o << "corpus/" << fileIndex++ << ".sample";
52 std::string s = o.str();
53
54 // Must match the input format of the fuzzer
55 FILE *f = fopen(s.c_str(), "w");
56 fwrite(&type, sizeof(type), 1, f);
57 fwrite(&spec, sizeof(spec), 1, f);
58 fwrite(&output, sizeof(output), 1, f);
59 fwrite(&options, sizeof(options), 1, f);
60
61 char zero[128 - 20] = {0};
62 fwrite(&zero, 128 - 20, 1, f);
63
64 for (size_t i = 0; i < numStrings; i++)
65 {
66 fwrite(shaderStrings[i], sizeof(char), strlen(shaderStrings[i]), f);
67 }
68 fwrite(&zero, 1, 1, f);
69
70 fclose(f);
71}
72#endif // defined(ANGLE_ENABLE_FUZZER_CORPUS_OUTPUT)
73} // anonymous namespace
74
Jamie Madill5508f392014-02-20 13:31:36 -050075bool IsWebGLBasedSpec(ShShaderSpec spec)
maxvujovic@gmail.com430f5e02012-06-08 17:47:59 +000076{
Qiankun Miaoc2c5fc42016-08-31 15:24:22 +080077 return (spec == SH_WEBGL_SPEC || spec == SH_WEBGL2_SPEC || spec == SH_WEBGL3_SPEC);
maxvujovic@gmail.com430f5e02012-06-08 17:47:59 +000078}
79
Qingqing Dengad0d0792015-04-08 14:25:06 -070080bool IsGLSL130OrNewer(ShShaderOutput output)
81{
82 return (output == SH_GLSL_130_OUTPUT ||
Geoff Lang8273e002015-06-15 13:40:19 -070083 output == SH_GLSL_140_OUTPUT ||
84 output == SH_GLSL_150_CORE_OUTPUT ||
85 output == SH_GLSL_330_CORE_OUTPUT ||
86 output == SH_GLSL_400_CORE_OUTPUT ||
Qingqing Dengad0d0792015-04-08 14:25:06 -070087 output == SH_GLSL_410_CORE_OUTPUT ||
Geoff Lang8273e002015-06-15 13:40:19 -070088 output == SH_GLSL_420_CORE_OUTPUT ||
89 output == SH_GLSL_430_CORE_OUTPUT ||
90 output == SH_GLSL_440_CORE_OUTPUT ||
91 output == SH_GLSL_450_CORE_OUTPUT);
Qingqing Dengad0d0792015-04-08 14:25:06 -070092}
93
Zhenyao Mo7faf1a12014-04-25 18:03:56 -070094size_t GetGlobalMaxTokenSize(ShShaderSpec spec)
Jamie Madill88f6e942014-02-19 10:27:53 -050095{
Jamie Madill88f6e942014-02-19 10:27:53 -050096 // WebGL defines a max token legnth of 256, while ES2 leaves max token
97 // size undefined. ES3 defines a max size of 1024 characters.
Zhenyao Modb9b40b2014-10-29 15:00:04 -070098 switch (spec)
Jamie Madill88f6e942014-02-19 10:27:53 -050099 {
Zhenyao Modb9b40b2014-10-29 15:00:04 -0700100 case SH_WEBGL_SPEC:
Jamie Madill88f6e942014-02-19 10:27:53 -0500101 return 256;
Zhenyao Modb9b40b2014-10-29 15:00:04 -0700102 default:
Jamie Madill88f6e942014-02-19 10:27:53 -0500103 return 1024;
104 }
105}
106
alokp@chromium.orgbafcbaa2010-11-23 19:07:43 +0000107namespace {
Zhenyao Modb9b40b2014-10-29 15:00:04 -0700108
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800109class TScopedPoolAllocator
110{
111 public:
112 TScopedPoolAllocator(TPoolAllocator* allocator) : mAllocator(allocator)
113 {
Alok Priyadarshibc3f1ac2013-09-23 14:57:02 -0400114 mAllocator->push();
alokp@chromium.orgbafcbaa2010-11-23 19:07:43 +0000115 SetGlobalPoolAllocator(mAllocator);
116 }
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800117 ~TScopedPoolAllocator()
118 {
alokp@chromium.orgbafcbaa2010-11-23 19:07:43 +0000119 SetGlobalPoolAllocator(NULL);
Alok Priyadarshibc3f1ac2013-09-23 14:57:02 -0400120 mAllocator->pop();
alokp@chromium.orgbafcbaa2010-11-23 19:07:43 +0000121 }
122
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800123 private:
alokp@chromium.orgbafcbaa2010-11-23 19:07:43 +0000124 TPoolAllocator* mAllocator;
Alok Priyadarshibc3f1ac2013-09-23 14:57:02 -0400125};
126
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800127class TScopedSymbolTableLevel
128{
129 public:
130 TScopedSymbolTableLevel(TSymbolTable* table) : mTable(table)
131 {
Alok Priyadarshibc3f1ac2013-09-23 14:57:02 -0400132 ASSERT(mTable->atBuiltInLevel());
133 mTable->push();
134 }
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800135 ~TScopedSymbolTableLevel()
136 {
Alok Priyadarshibc3f1ac2013-09-23 14:57:02 -0400137 while (!mTable->atBuiltInLevel())
138 mTable->pop();
139 }
140
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800141 private:
Alok Priyadarshibc3f1ac2013-09-23 14:57:02 -0400142 TSymbolTable* mTable;
alokp@chromium.orgbafcbaa2010-11-23 19:07:43 +0000143};
Zhenyao Modb9b40b2014-10-29 15:00:04 -0700144
145int MapSpecToShaderVersion(ShShaderSpec spec)
146{
147 switch (spec)
148 {
149 case SH_GLES2_SPEC:
150 case SH_WEBGL_SPEC:
Zhenyao Modb9b40b2014-10-29 15:00:04 -0700151 return 100;
152 case SH_GLES3_SPEC:
153 case SH_WEBGL2_SPEC:
154 return 300;
Martin Radev1be913c2016-07-11 17:59:16 +0300155 case SH_GLES3_1_SPEC:
156 case SH_WEBGL3_SPEC:
157 return 310;
Zhenyao Modb9b40b2014-10-29 15:00:04 -0700158 default:
159 UNREACHABLE();
160 return 0;
161 }
162}
163
alokp@chromium.orgbafcbaa2010-11-23 19:07:43 +0000164} // namespace
165
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800166TShHandleBase::TShHandleBase()
167{
alokp@chromium.orgbafcbaa2010-11-23 19:07:43 +0000168 allocator.push();
169 SetGlobalPoolAllocator(&allocator);
170}
171
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800172TShHandleBase::~TShHandleBase()
173{
alokp@chromium.orgbafcbaa2010-11-23 19:07:43 +0000174 SetGlobalPoolAllocator(NULL);
175 allocator.popAll();
176}
177
Jamie Madill183bde52014-07-02 15:31:19 -0400178TCompiler::TCompiler(sh::GLenum type, ShShaderSpec spec, ShShaderOutput output)
Kenneth Russellbccc65d2016-07-19 16:48:43 -0700179 : variablesCollected(false),
180 shaderType(type),
zmo@google.comf420c422011-09-12 18:27:59 +0000181 shaderSpec(spec),
Jamie Madill68fe74a2014-05-27 12:56:01 -0400182 outputType(output),
Jamie Madilleb1a0102013-07-08 13:31:38 -0400183 maxUniformVectors(0),
184 maxExpressionComplexity(0),
185 maxCallStackDepth(0),
Olli Etuaho19d1dc92016-03-08 17:18:46 +0200186 maxFunctionParameters(0),
shannon.woods%transgaming.com@gtempaccount.comcbb6b6a2013-04-13 03:27:47 +0000187 fragmentPrecisionHigh(false),
shannon.woods@transgaming.com1d432bb2013-01-25 21:57:28 +0000188 clampingStrategy(SH_CLAMP_WITH_CLAMP_INTRINSIC),
Olli Etuaho8efc5ad2015-03-03 17:21:10 +0200189 builtInFunctionEmulator(),
Corentin Wallezd4b50542015-09-28 12:19:26 -0700190 mSourcePath(NULL),
Martin Radev802abe02016-08-04 17:48:32 +0300191 mComputeShaderLocalSizeDeclared(false),
Corentin Wallezd4b50542015-09-28 12:19:26 -0700192 mTemporaryIndex(0)
alokp@chromium.org4888ceb2010-10-01 21:13:12 +0000193{
Martin Radev802abe02016-08-04 17:48:32 +0300194 mComputeShaderLocalSize.fill(1);
alokp@chromium.org4888ceb2010-10-01 21:13:12 +0000195}
196
197TCompiler::~TCompiler()
198{
199}
200
Qiankun Miao7ebb97f2016-09-08 18:01:50 +0800201bool TCompiler::shouldRunLoopAndIndexingValidation(ShCompileOptions compileOptions) const
Olli Etuaho5d91dda2015-06-18 15:47:46 +0300202{
203 // If compiling an ESSL 1.00 shader for WebGL, or if its been requested through the API,
204 // validate loop and indexing as well (to verify that the shader only uses minimal functionality
205 // of ESSL 1.00 as in Appendix A of the spec).
206 return (IsWebGLBasedSpec(shaderSpec) && shaderVersion == 100) ||
207 (compileOptions & SH_VALIDATE_LOOP_INDEXING);
208}
209
alokp@chromium.org4888ceb2010-10-01 21:13:12 +0000210bool TCompiler::Init(const ShBuiltInResources& resources)
alokp@chromium.org07620a52010-09-23 17:53:56 +0000211{
shannon.woods%transgaming.com@gtempaccount.com0bbed382013-04-13 03:38:07 +0000212 shaderVersion = 100;
Jamie Madill183bde52014-07-02 15:31:19 -0400213 maxUniformVectors = (shaderType == GL_VERTEX_SHADER) ?
gman@chromium.org8d804792012-10-17 21:33:48 +0000214 resources.MaxVertexUniformVectors :
215 resources.MaxFragmentUniformVectors;
Jamie Madilleb1a0102013-07-08 13:31:38 -0400216 maxExpressionComplexity = resources.MaxExpressionComplexity;
Olli Etuaho19d1dc92016-03-08 17:18:46 +0200217 maxCallStackDepth = resources.MaxCallStackDepth;
218 maxFunctionParameters = resources.MaxFunctionParameters;
Alok Priyadarshibc3f1ac2013-09-23 14:57:02 -0400219
220 SetGlobalPoolAllocator(&allocator);
alokp@chromium.orgbafcbaa2010-11-23 19:07:43 +0000221
alokp@chromium.org07620a52010-09-23 17:53:56 +0000222 // Generate built-in symbol table.
223 if (!InitBuiltInSymbolTable(resources))
224 return false;
alokp@chromium.org07620a52010-09-23 17:53:56 +0000225 InitExtensionBehavior(resources, extensionBehavior);
shannon.woods%transgaming.com@gtempaccount.comcbb6b6a2013-04-13 03:27:47 +0000226 fragmentPrecisionHigh = resources.FragmentPrecisionHigh == 1;
alokp@chromium.orgbafcbaa2010-11-23 19:07:43 +0000227
shannon.woods@transgaming.com1d432bb2013-01-25 21:57:28 +0000228 arrayBoundsClamper.SetClampingStrategy(resources.ArrayIndexClampingStrategy);
229 clampingStrategy = resources.ArrayIndexClampingStrategy;
230
daniel@transgaming.comc23f4612012-11-28 19:42:57 +0000231 hashFunction = resources.HashFunction;
232
alokp@chromium.org07620a52010-09-23 17:53:56 +0000233 return true;
234}
235
Olli Etuaho6d40bbd2016-09-30 13:49:38 +0100236TIntermBlock *TCompiler::compileTreeForTesting(const char *const shaderStrings[],
237 size_t numStrings,
238 ShCompileOptions compileOptions)
alokp@chromium.org07620a52010-09-23 17:53:56 +0000239{
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200240 return compileTreeImpl(shaderStrings, numStrings, compileOptions);
241}
242
Olli Etuaho6d40bbd2016-09-30 13:49:38 +0100243TIntermBlock *TCompiler::compileTreeImpl(const char *const shaderStrings[],
244 size_t numStrings,
245 const ShCompileOptions compileOptions)
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200246{
alokp@chromium.org07620a52010-09-23 17:53:56 +0000247 clearResults();
248
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200249 ASSERT(numStrings > 0);
250 ASSERT(GetGlobalPoolAllocator());
alokp@chromium.org07620a52010-09-23 17:53:56 +0000251
David Yen0fbd1282015-02-02 14:46:09 -0800252 // Reset the extension behavior for each compilation unit.
253 ResetExtensionBehavior(extensionBehavior);
254
apatrick@chromium.org0f4cefe2011-01-26 19:30:57 +0000255 // First string is path of source file if flag is set. The actual source follows.
shannon.woods@transgaming.comd64b3da2013-02-28 23:19:26 +0000256 size_t firstSource = 0;
apatrick@chromium.org0f4cefe2011-01-26 19:30:57 +0000257 if (compileOptions & SH_SOURCE_PATH)
258 {
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200259 mSourcePath = shaderStrings[0];
apatrick@chromium.org0f4cefe2011-01-26 19:30:57 +0000260 ++firstSource;
261 }
262
Olli Etuahof119a262016-08-19 15:54:22 +0300263 TParseContext parseContext(symbolTable, extensionBehavior, shaderType, shaderSpec,
Olli Etuahoe1a94c62015-11-16 17:35:25 +0200264 compileOptions, true, infoSink, getResources());
Olli Etuaho853dc1a2014-11-06 17:25:48 +0200265
Olli Etuahoa6996682015-10-12 14:32:30 +0300266 parseContext.setFragmentPrecisionHighOnESSL1(fragmentPrecisionHigh);
Alok Priyadarshi8156b6b2013-09-23 14:56:58 -0400267 SetGlobalParseContext(&parseContext);
alokp@chromium.org07620a52010-09-23 17:53:56 +0000268
269 // We preserve symbols at the built-in level from compile-to-compile.
270 // Start pushing the user-defined symbols at global level.
Alok Priyadarshibc3f1ac2013-09-23 14:57:02 -0400271 TScopedSymbolTableLevel scopedSymbolLevel(&symbolTable);
alokp@chromium.org07620a52010-09-23 17:53:56 +0000272
273 // Parse shader.
274 bool success =
Jamie Madill6e06b1f2015-05-14 10:01:17 -0400275 (PaParseStrings(numStrings - firstSource, &shaderStrings[firstSource], nullptr, &parseContext) == 0) &&
276 (parseContext.getTreeRoot() != nullptr);
shannon.woods%transgaming.com@gtempaccount.com0bbed382013-04-13 03:38:07 +0000277
shannon.woods%transgaming.com@gtempaccount.com5524db02013-04-13 03:38:16 +0000278 shaderVersion = parseContext.getShaderVersion();
Zhenyao Modb9b40b2014-10-29 15:00:04 -0700279 if (success && MapSpecToShaderVersion(shaderSpec) < shaderVersion)
280 {
281 infoSink.info.prefix(EPrefixError);
282 infoSink.info << "unsupported shader version";
283 success = false;
284 }
shannon.woods%transgaming.com@gtempaccount.com0bbed382013-04-13 03:38:07 +0000285
Olli Etuaho6d40bbd2016-09-30 13:49:38 +0100286 TIntermBlock *root = nullptr;
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200287
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800288 if (success)
289 {
Zhenyao Mo94ac7b72014-10-15 18:22:08 -0700290 mPragma = parseContext.pragma();
Kenneth Russell8bad46d2016-07-01 19:52:52 -0700291 symbolTable.setGlobalInvariant(mPragma.stdgl.invariantAll);
Zhenyao Mo94ac7b72014-10-15 18:22:08 -0700292
Martin Radev802abe02016-08-04 17:48:32 +0300293 mComputeShaderLocalSizeDeclared = parseContext.isComputeShaderLocalSizeDeclared();
294 mComputeShaderLocalSize = parseContext.getComputeShaderLocalSize();
295
Jamie Madill6e06b1f2015-05-14 10:01:17 -0400296 root = parseContext.getTreeRoot();
alokp@chromium.orgb59a7782010-11-24 18:38:33 +0000297
Olli Etuahoa6996682015-10-12 14:32:30 +0300298 // Highp might have been auto-enabled based on shader version
299 fragmentPrecisionHigh = parseContext.getFragmentPrecisionHigh();
300
Jamie Madill6654bc92014-03-26 14:01:57 -0400301 // Disallow expressions deemed too complex.
302 if (success && (compileOptions & SH_LIMIT_EXPRESSION_COMPLEXITY))
303 success = limitExpressionComplexity(root);
304
Corentin Wallez71d147f2015-02-11 11:15:24 -0800305 // Create the function DAG and check there is no recursion
zmo@google.comb1762df2011-07-30 02:04:23 +0000306 if (success)
Corentin Wallez71d147f2015-02-11 11:15:24 -0800307 success = initCallDag(root);
308
309 if (success && (compileOptions & SH_LIMIT_CALL_STACK_DEPTH))
310 success = checkCallDepth();
311
312 // Checks which functions are used and if "main" exists
313 if (success)
314 {
315 functionMetadata.clear();
316 functionMetadata.resize(mCallDag.size());
317 success = tagUsedFunctions();
318 }
zmo@google.comb1762df2011-07-30 02:04:23 +0000319
Corentin Walleza094a8a2015-04-07 11:53:06 -0700320 if (success && !(compileOptions & SH_DONT_PRUNE_UNUSED_FUNCTIONS))
321 success = pruneUnusedFunctions(root);
322
Olli Etuahoc6833112015-04-22 15:15:54 +0300323 // Prune empty declarations to work around driver bugs and to keep declaration output simple.
324 if (success)
325 PruneEmptyDeclarations(root);
326
Jamie Madill183bde52014-07-02 15:31:19 -0400327 if (success && shaderVersion == 300 && shaderType == GL_FRAGMENT_SHADER)
Jamie Madill05a80ce2013-06-20 11:55:49 -0400328 success = validateOutputs(root);
329
Olli Etuaho5d91dda2015-06-18 15:47:46 +0300330 if (success && shouldRunLoopAndIndexingValidation(compileOptions))
alokp@chromium.orgb59a7782010-11-24 18:38:33 +0000331 success = validateLimitations(root);
alokp@chromium.org07620a52010-09-23 17:53:56 +0000332
Jamie Madilld5696192016-10-06 11:09:24 -0400333 // Fail compilation if precision emulation not supported.
334 if (success && getResources().WEBGL_debug_shader_precision &&
335 getPragma().debugShaderPrecision)
336 {
337 if (!EmulatePrecision::SupportedInLanguage(outputType))
338 {
339 infoSink.info.prefix(EPrefixError);
340 infoSink.info << "Precision emulation not supported for this output type.";
341 success = false;
342 }
343 }
344
zmo@google.com0c6bb7a2011-08-17 19:39:58 +0000345 // Unroll for-loop markup needs to happen after validateLimitations pass.
346 if (success && (compileOptions & SH_UNROLL_FOR_LOOP_WITH_INTEGER_INDEX))
Zhenyao Mo3cdfcce2014-03-07 13:00:08 -0800347 {
Olli Etuaho8a76dcc2015-12-10 20:25:12 +0200348 ForLoopUnrollMarker marker(ForLoopUnrollMarker::kIntegerIndex,
349 shouldRunLoopAndIndexingValidation(compileOptions));
Zhenyao Mo550c6002014-02-26 15:40:48 -0800350 root->traverse(&marker);
351 }
352 if (success && (compileOptions & SH_UNROLL_FOR_LOOP_WITH_SAMPLER_ARRAY_INDEX))
Zhenyao Mo3cdfcce2014-03-07 13:00:08 -0800353 {
Olli Etuaho8a76dcc2015-12-10 20:25:12 +0200354 ForLoopUnrollMarker marker(ForLoopUnrollMarker::kSamplerArrayIndex,
355 shouldRunLoopAndIndexingValidation(compileOptions));
Zhenyao Mo550c6002014-02-26 15:40:48 -0800356 root->traverse(&marker);
357 if (marker.samplerArrayIndexIsFloatLoopIndex())
358 {
359 infoSink.info.prefix(EPrefixError);
360 infoSink.info << "sampler array index is float loop index";
361 success = false;
362 }
363 }
zmo@google.com0c6bb7a2011-08-17 19:39:58 +0000364
zmo@google.com32e97312011-08-24 01:03:11 +0000365 // Built-in function emulation needs to happen after validateLimitations pass.
Olli Etuaho8efc5ad2015-03-03 17:21:10 +0200366 if (success)
367 {
Jamie Madill438dbcf2016-06-17 14:20:05 -0400368 // TODO(jmadill): Remove global pool allocator.
369 GetGlobalPoolAllocator()->lock();
Olli Etuaho8efc5ad2015-03-03 17:21:10 +0200370 initBuiltInFunctionEmulator(&builtInFunctionEmulator, compileOptions);
Jamie Madill438dbcf2016-06-17 14:20:05 -0400371 GetGlobalPoolAllocator()->unlock();
zmo@google.com32e97312011-08-24 01:03:11 +0000372 builtInFunctionEmulator.MarkBuiltInFunctionsForEmulation(root);
Olli Etuaho8efc5ad2015-03-03 17:21:10 +0200373 }
zmo@google.com32e97312011-08-24 01:03:11 +0000374
daniel@transgaming.com4167cc92013-01-11 04:11:53 +0000375 // Clamping uniform array bounds needs to happen after validateLimitations pass.
376 if (success && (compileOptions & SH_CLAMP_INDIRECT_ARRAY_BOUNDS))
377 arrayBoundsClamper.MarkIndirectArrayBoundsForClamping(root);
378
Ian Ewell924b7de2016-01-21 13:54:28 -0500379 // gl_Position is always written in compatibility output mode
380 if (success && shaderType == GL_VERTEX_SHADER &&
381 ((compileOptions & SH_INIT_GL_POSITION) ||
382 (outputType == SH_GLSL_COMPATIBILITY_OUTPUT)))
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800383 initializeGLPosition(root);
Zhenyao Moac44cd22013-09-23 14:57:09 -0400384
Corentin Wallezd4b50542015-09-28 12:19:26 -0700385 // This pass might emit short circuits so keep it before the short circuit unfolding
386 if (success && (compileOptions & SH_REWRITE_DO_WHILE_LOOPS))
387 RewriteDoWhile(root, getTemporaryIndex());
388
Qiankun Miao09cfac62016-09-06 17:25:16 +0800389 if (success && (compileOptions & SH_ADD_AND_TRUE_TO_LOOP_CONDITION))
390 sh::AddAndTrueToLoopCondition(root);
391
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800392 if (success && (compileOptions & SH_UNFOLD_SHORT_CIRCUIT))
393 {
Zhenyao Mo7cab38b2013-10-15 12:59:30 -0700394 UnfoldShortCircuitAST unfoldShortCircuit;
395 root->traverse(&unfoldShortCircuit);
396 unfoldShortCircuit.updateTree();
397 }
398
Olli Etuaho5c407bb2015-06-01 12:20:39 +0300399 if (success && (compileOptions & SH_REMOVE_POW_WITH_CONSTANT_EXPONENT))
400 {
401 RemovePow(root);
402 }
403
Olli Etuaho4dfe8092015-08-21 17:44:35 +0300404 if (success && shouldCollectVariables(compileOptions))
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800405 {
Zhenyao Mo74da9f22013-09-23 14:57:01 -0400406 collectVariables(root);
Qin Jiajia7835b522016-10-08 11:20:17 +0800407 if (compileOptions & SH_USE_UNUSED_STANDARD_SHARED_BLOCKS)
408 {
409 useAllMembersInUnusedStandardAndSharedBlocks(root);
410 }
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800411 if (compileOptions & SH_ENFORCE_PACKING_RESTRICTIONS)
412 {
gman@chromium.org8d804792012-10-17 21:33:48 +0000413 success = enforcePackingRestrictions();
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800414 if (!success)
415 {
Jamie Madill075edd82013-07-08 13:30:19 -0400416 infoSink.info.prefix(EPrefixError);
417 infoSink.info << "too many uniforms";
gman@chromium.org8d804792012-10-17 21:33:48 +0000418 }
419 }
Zhenyao Mo72111912016-07-20 17:45:56 -0700420 if (success && (compileOptions & SH_INIT_OUTPUT_VARIABLES))
421 {
Olli Etuaho27776e32016-07-22 14:00:56 +0300422 initializeOutputVariables(root);
Zhenyao Mo72111912016-07-20 17:45:56 -0700423 }
gman@chromium.org8d804792012-10-17 21:33:48 +0000424 }
zmo@google.comfd747b82011-04-23 01:30:07 +0000425
Zhenyao Mocd68fe72014-07-11 10:45:44 -0700426 if (success && (compileOptions & SH_SCALARIZE_VEC_AND_MAT_CONSTRUCTOR_ARGS))
427 {
Zhenyao Modaf56572014-08-06 16:18:30 -0700428 ScalarizeVecAndMatConstructorArgs scalarizer(
429 shaderType, fragmentPrecisionHigh);
Zhenyao Mocd68fe72014-07-11 10:45:44 -0700430 root->traverse(&scalarizer);
431 }
432
Zhenyao Moe740add2014-07-18 17:01:01 -0700433 if (success && (compileOptions & SH_REGENERATE_STRUCT_NAMES))
434 {
435 RegenerateStructNames gen(symbolTable, shaderVersion);
436 root->traverse(&gen);
437 }
Olli Etuaho3d932d82016-04-12 11:10:30 +0300438
Zhenyao Mo4e94fea2016-08-09 14:31:37 -0700439 if (success && shaderType == GL_FRAGMENT_SHADER && shaderVersion == 100 &&
440 compileResources.EXT_draw_buffers && compileResources.MaxDrawBuffers > 1 &&
441 IsExtensionEnabled(extensionBehavior, "GL_EXT_draw_buffers"))
442 {
443 EmulateGLFragColorBroadcast(root, compileResources.MaxDrawBuffers, &outputVariables);
444 }
445
Olli Etuaho3d932d82016-04-12 11:10:30 +0300446 if (success)
447 {
448 DeferGlobalInitializers(root);
449 }
alokp@chromium.org07620a52010-09-23 17:53:56 +0000450 }
451
Zhenyao Mo7faf1a12014-04-25 18:03:56 -0700452 SetGlobalParseContext(NULL);
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200453 if (success)
454 return root;
455
456 return NULL;
457}
458
Qiankun Miao7ebb97f2016-09-08 18:01:50 +0800459bool TCompiler::compile(const char *const shaderStrings[],
460 size_t numStrings,
461 ShCompileOptions compileOptionsIn)
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200462{
Corentin Wallez28b65282016-06-16 07:24:50 -0700463#if defined(ANGLE_ENABLE_FUZZER_CORPUS_OUTPUT)
464 DumpFuzzerCase(shaderStrings, numStrings, shaderType, shaderSpec, outputType, compileOptionsIn);
465#endif // defined(ANGLE_ENABLE_FUZZER_CORPUS_OUTPUT)
466
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200467 if (numStrings == 0)
468 return true;
469
Qiankun Miao7ebb97f2016-09-08 18:01:50 +0800470 ShCompileOptions compileOptions = compileOptionsIn;
Kenneth Russellbccc65d2016-07-19 16:48:43 -0700471
472 // Apply key workarounds.
473 if (shouldFlattenPragmaStdglInvariantAll())
474 {
475 // This should be harmless to do in all cases, but for the moment, do it only conditionally.
476 compileOptions |= SH_FLATTEN_PRAGMA_STDGL_INVARIANT_ALL;
477 }
478
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200479 TScopedPoolAllocator scopedAlloc(&allocator);
Olli Etuaho6d40bbd2016-09-30 13:49:38 +0100480 TIntermBlock *root = compileTreeImpl(shaderStrings, numStrings, compileOptions);
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200481
482 if (root)
483 {
484 if (compileOptions & SH_INTERMEDIATE_TREE)
485 TIntermediate::outputTree(root, infoSink.info);
486
487 if (compileOptions & SH_OBJECT_CODE)
488 translate(root, compileOptions);
489
490 // The IntermNode tree doesn't need to be deleted here, since the
491 // memory will be freed in a big chunk by the PoolAllocator.
492 return true;
493 }
494 return false;
alokp@chromium.org07620a52010-09-23 17:53:56 +0000495}
496
Nicolas Capens49a88872013-06-20 09:54:03 -0400497bool TCompiler::InitBuiltInSymbolTable(const ShBuiltInResources &resources)
alokp@chromium.org07620a52010-09-23 17:53:56 +0000498{
shannon.woods%transgaming.com@gtempaccount.com18b4c4b2013-04-13 03:31:40 +0000499 compileResources = resources;
Shannon Woods2d76e5f2014-05-16 17:46:41 -0400500 setResourceString();
shannonwoods@chromium.org2ac0be92013-05-30 00:02:27 +0000501
Nicolas Capens49a88872013-06-20 09:54:03 -0400502 assert(symbolTable.isEmpty());
503 symbolTable.push(); // COMMON_BUILTINS
504 symbolTable.push(); // ESSL1_BUILTINS
505 symbolTable.push(); // ESSL3_BUILTINS
Martin Radeve93d24e2016-07-28 12:06:05 +0300506 symbolTable.push(); // ESSL3_1_BUILTINS
shannonwoods@chromium.org2ac0be92013-05-30 00:02:27 +0000507
Nicolas Capens49a88872013-06-20 09:54:03 -0400508 TPublicType integer;
Martin Radev4a9cd802016-09-01 16:51:51 +0300509 integer.setBasicType(EbtInt);
510 integer.initializeSizeForScalarTypes();
Nicolas Capens49a88872013-06-20 09:54:03 -0400511 integer.array = false;
512
513 TPublicType floatingPoint;
Martin Radev4a9cd802016-09-01 16:51:51 +0300514 floatingPoint.setBasicType(EbtFloat);
515 floatingPoint.initializeSizeForScalarTypes();
Nicolas Capens49a88872013-06-20 09:54:03 -0400516 floatingPoint.array = false;
517
518 switch(shaderType)
519 {
Jamie Madill183bde52014-07-02 15:31:19 -0400520 case GL_FRAGMENT_SHADER:
Nicolas Capens49a88872013-06-20 09:54:03 -0400521 symbolTable.setDefaultPrecision(integer, EbpMedium);
522 break;
Jamie Madill183bde52014-07-02 15:31:19 -0400523 case GL_VERTEX_SHADER:
Nicolas Capens49a88872013-06-20 09:54:03 -0400524 symbolTable.setDefaultPrecision(integer, EbpHigh);
525 symbolTable.setDefaultPrecision(floatingPoint, EbpHigh);
526 break;
Martin Radev802abe02016-08-04 17:48:32 +0300527 case GL_COMPUTE_SHADER:
528 symbolTable.setDefaultPrecision(integer, EbpHigh);
529 symbolTable.setDefaultPrecision(floatingPoint, EbpHigh);
530 break;
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800531 default:
532 assert(false && "Language not supported");
Nicolas Capens49a88872013-06-20 09:54:03 -0400533 }
Olli Etuaho183d7e22015-11-20 15:59:09 +0200534 // Set defaults for sampler types that have default precision, even those that are
Zhenyao Moa5a1dfc2013-09-23 14:57:03 -0400535 // only available if an extension exists.
Olli Etuaho183d7e22015-11-20 15:59:09 +0200536 // New sampler types in ESSL3 don't have default precision. ESSL1 types do.
537 initSamplerDefaultPrecision(EbtSampler2D);
538 initSamplerDefaultPrecision(EbtSamplerCube);
539 // SamplerExternalOES is specified in the extension to have default precision.
540 initSamplerDefaultPrecision(EbtSamplerExternalOES);
541 // It isn't specified whether Sampler2DRect has default precision.
542 initSamplerDefaultPrecision(EbtSampler2DRect);
Nicolas Capens49a88872013-06-20 09:54:03 -0400543
Jamie Madill1b452142013-07-12 14:51:11 -0400544 InsertBuiltInFunctions(shaderType, shaderSpec, resources, symbolTable);
Nicolas Capens49a88872013-06-20 09:54:03 -0400545
546 IdentifyBuiltIns(shaderType, shaderSpec, resources, symbolTable);
547
548 return true;
alokp@chromium.org07620a52010-09-23 17:53:56 +0000549}
550
Olli Etuaho183d7e22015-11-20 15:59:09 +0200551void TCompiler::initSamplerDefaultPrecision(TBasicType samplerType)
552{
553 ASSERT(samplerType > EbtGuardSamplerBegin && samplerType < EbtGuardSamplerEnd);
554 TPublicType sampler;
Martin Radev4a9cd802016-09-01 16:51:51 +0300555 sampler.initializeSizeForScalarTypes();
556 sampler.setBasicType(samplerType);
Olli Etuaho183d7e22015-11-20 15:59:09 +0200557 sampler.array = false;
Olli Etuaho183d7e22015-11-20 15:59:09 +0200558 symbolTable.setDefaultPrecision(sampler, EbpLow);
559}
560
Shannon Woods2d76e5f2014-05-16 17:46:41 -0400561void TCompiler::setResourceString()
562{
563 std::ostringstream strstream;
Geoff Langb66a9092016-05-16 15:59:14 -0400564
565 // clang-format off
Shannon Woods2d76e5f2014-05-16 17:46:41 -0400566 strstream << ":MaxVertexAttribs:" << compileResources.MaxVertexAttribs
567 << ":MaxVertexUniformVectors:" << compileResources.MaxVertexUniformVectors
568 << ":MaxVaryingVectors:" << compileResources.MaxVaryingVectors
569 << ":MaxVertexTextureImageUnits:" << compileResources.MaxVertexTextureImageUnits
570 << ":MaxCombinedTextureImageUnits:" << compileResources.MaxCombinedTextureImageUnits
571 << ":MaxTextureImageUnits:" << compileResources.MaxTextureImageUnits
572 << ":MaxFragmentUniformVectors:" << compileResources.MaxFragmentUniformVectors
573 << ":MaxDrawBuffers:" << compileResources.MaxDrawBuffers
574 << ":OES_standard_derivatives:" << compileResources.OES_standard_derivatives
575 << ":OES_EGL_image_external:" << compileResources.OES_EGL_image_external
Geoff Langb66a9092016-05-16 15:59:14 -0400576 << ":OES_EGL_image_external_essl3:" << compileResources.OES_EGL_image_external_essl3
577 << ":NV_EGL_stream_consumer_external:" << compileResources.NV_EGL_stream_consumer_external
Shannon Woods2d76e5f2014-05-16 17:46:41 -0400578 << ":ARB_texture_rectangle:" << compileResources.ARB_texture_rectangle
579 << ":EXT_draw_buffers:" << compileResources.EXT_draw_buffers
580 << ":FragmentPrecisionHigh:" << compileResources.FragmentPrecisionHigh
581 << ":MaxExpressionComplexity:" << compileResources.MaxExpressionComplexity
582 << ":MaxCallStackDepth:" << compileResources.MaxCallStackDepth
Olli Etuaho19d1dc92016-03-08 17:18:46 +0200583 << ":MaxFunctionParameters:" << compileResources.MaxFunctionParameters
Kimmo Kinnunenb18609b2015-07-16 14:13:11 +0300584 << ":EXT_blend_func_extended:" << compileResources.EXT_blend_func_extended
Shannon Woods2d76e5f2014-05-16 17:46:41 -0400585 << ":EXT_frag_depth:" << compileResources.EXT_frag_depth
586 << ":EXT_shader_texture_lod:" << compileResources.EXT_shader_texture_lod
Erik Dahlströmea7a2122014-11-17 16:15:57 +0100587 << ":EXT_shader_framebuffer_fetch:" << compileResources.EXT_shader_framebuffer_fetch
588 << ":NV_shader_framebuffer_fetch:" << compileResources.NV_shader_framebuffer_fetch
589 << ":ARM_shader_framebuffer_fetch:" << compileResources.ARM_shader_framebuffer_fetch
Shannon Woods2d76e5f2014-05-16 17:46:41 -0400590 << ":MaxVertexOutputVectors:" << compileResources.MaxVertexOutputVectors
591 << ":MaxFragmentInputVectors:" << compileResources.MaxFragmentInputVectors
592 << ":MinProgramTexelOffset:" << compileResources.MinProgramTexelOffset
Olli Etuahoe61209a2014-09-26 12:01:17 +0300593 << ":MaxProgramTexelOffset:" << compileResources.MaxProgramTexelOffset
Kimmo Kinnunenb18609b2015-07-16 14:13:11 +0300594 << ":MaxDualSourceDrawBuffers:" << compileResources.MaxDualSourceDrawBuffers
Olli Etuaho853dc1a2014-11-06 17:25:48 +0200595 << ":NV_draw_buffers:" << compileResources.NV_draw_buffers
Martin Radeve93d24e2016-07-28 12:06:05 +0300596 << ":WEBGL_debug_shader_precision:" << compileResources.WEBGL_debug_shader_precision
597 << ":MaxImageUnits:" << compileResources.MaxImageUnits
598 << ":MaxVertexImageUniforms:" << compileResources.MaxVertexImageUniforms
599 << ":MaxFragmentImageUniforms:" << compileResources.MaxFragmentImageUniforms
600 << ":MaxComputeImageUniforms:" << compileResources.MaxComputeImageUniforms
601 << ":MaxCombinedImageUniforms:" << compileResources.MaxCombinedImageUniforms
602 << ":MaxCombinedShaderOutputResources:" << compileResources.MaxCombinedShaderOutputResources
603 << ":MaxComputeWorkGroupCountX:" << compileResources.MaxComputeWorkGroupCount[0]
604 << ":MaxComputeWorkGroupCountY:" << compileResources.MaxComputeWorkGroupCount[1]
605 << ":MaxComputeWorkGroupCountZ:" << compileResources.MaxComputeWorkGroupCount[2]
606 << ":MaxComputeWorkGroupSizeX:" << compileResources.MaxComputeWorkGroupSize[0]
607 << ":MaxComputeWorkGroupSizeY:" << compileResources.MaxComputeWorkGroupSize[1]
608 << ":MaxComputeWorkGroupSizeZ:" << compileResources.MaxComputeWorkGroupSize[2]
609 << ":MaxComputeUniformComponents:" << compileResources.MaxComputeUniformComponents
610 << ":MaxComputeTextureImageUnits:" << compileResources.MaxComputeTextureImageUnits
611 << ":MaxComputeAtomicCounters:" << compileResources.MaxComputeAtomicCounters
612 << ":MaxComputeAtomicCounterBuffers:" << compileResources.MaxComputeAtomicCounterBuffers
613 << ":MaxVertexAtomicCounters:" << compileResources.MaxVertexAtomicCounters
614 << ":MaxFragmentAtomicCounters:" << compileResources.MaxFragmentAtomicCounters
615 << ":MaxCombinedAtomicCounters:" << compileResources.MaxCombinedAtomicCounters
616 << ":MaxAtomicCounterBindings:" << compileResources.MaxAtomicCounterBindings
617 << ":MaxVertexAtomicCounterBuffers:" << compileResources.MaxVertexAtomicCounterBuffers
618 << ":MaxFragmentAtomicCounterBuffers:" << compileResources.MaxFragmentAtomicCounterBuffers
619 << ":MaxCombinedAtomicCounterBuffers:" << compileResources.MaxCombinedAtomicCounterBuffers
620 << ":MaxAtomicCounterBufferSize:" << compileResources.MaxAtomicCounterBufferSize;
Geoff Langb66a9092016-05-16 15:59:14 -0400621 // clang-format on
Shannon Woods2d76e5f2014-05-16 17:46:41 -0400622
623 builtInResourcesString = strstream.str();
624}
625
alokp@chromium.org07620a52010-09-23 17:53:56 +0000626void TCompiler::clearResults()
627{
daniel@transgaming.com4167cc92013-01-11 04:11:53 +0000628 arrayBoundsClamper.Cleanup();
alokp@chromium.org07620a52010-09-23 17:53:56 +0000629 infoSink.info.erase();
630 infoSink.obj.erase();
631 infoSink.debug.erase();
632
Jamie Madilled27c722014-07-02 15:31:23 -0400633 attributes.clear();
634 outputVariables.clear();
alokp@chromium.org07620a52010-09-23 17:53:56 +0000635 uniforms.clear();
Jamie Madill23a8a432014-07-09 13:27:42 -0400636 expandedUniforms.clear();
Zhenyao Mod2d340b2013-09-23 14:57:05 -0400637 varyings.clear();
Jamie Madilled27c722014-07-02 15:31:23 -0400638 interfaceBlocks.clear();
Kenneth Russellbccc65d2016-07-19 16:48:43 -0700639 variablesCollected = false;
zmo@google.coma3b4ab42011-09-16 00:53:26 +0000640
641 builtInFunctionEmulator.Cleanup();
daniel@transgaming.com0aa3b5a2012-11-28 19:43:24 +0000642
643 nameMap.clear();
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200644
645 mSourcePath = NULL;
Corentin Wallezd4b50542015-09-28 12:19:26 -0700646 mTemporaryIndex = 0;
alokp@chromium.org07620a52010-09-23 17:53:56 +0000647}
648
Corentin Wallez71d147f2015-02-11 11:15:24 -0800649bool TCompiler::initCallDag(TIntermNode *root)
zmo@google.comb1762df2011-07-30 02:04:23 +0000650{
Corentin Wallez71d147f2015-02-11 11:15:24 -0800651 mCallDag.clear();
652
653 switch (mCallDag.init(root, &infoSink.info))
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800654 {
Corentin Wallez71d147f2015-02-11 11:15:24 -0800655 case CallDAG::INITDAG_SUCCESS:
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800656 return true;
Corentin Wallez71d147f2015-02-11 11:15:24 -0800657 case CallDAG::INITDAG_RECURSION:
658 infoSink.info.prefix(EPrefixError);
659 infoSink.info << "Function recursion detected";
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800660 return false;
Corentin Wallez71d147f2015-02-11 11:15:24 -0800661 case CallDAG::INITDAG_UNDEFINED:
662 infoSink.info.prefix(EPrefixError);
663 infoSink.info << "Unimplemented function detected";
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800664 return false;
Corentin Wallez71d147f2015-02-11 11:15:24 -0800665 }
666
667 UNREACHABLE();
668 return true;
669}
670
671bool TCompiler::checkCallDepth()
672{
673 std::vector<int> depths(mCallDag.size());
674
675 for (size_t i = 0; i < mCallDag.size(); i++)
676 {
677 int depth = 0;
678 auto &record = mCallDag.getRecordFromIndex(i);
679
680 for (auto &calleeIndex : record.callees)
681 {
682 depth = std::max(depth, depths[calleeIndex] + 1);
683 }
684
685 depths[i] = depth;
686
687 if (depth >= maxCallStackDepth)
688 {
689 // Trace back the function chain to have a meaningful info log.
690 infoSink.info.prefix(EPrefixError);
691 infoSink.info << "Call stack too deep (larger than " << maxCallStackDepth
692 << ") with the following call chain: " << record.name;
693
Cooper Partin4d61f7e2015-08-12 10:56:50 -0700694 int currentFunction = static_cast<int>(i);
Corentin Wallez71d147f2015-02-11 11:15:24 -0800695 int currentDepth = depth;
696
697 while (currentFunction != -1)
698 {
699 infoSink.info << " -> " << mCallDag.getRecordFromIndex(currentFunction).name;
700
701 int nextFunction = -1;
702 for (auto& calleeIndex : mCallDag.getRecordFromIndex(currentFunction).callees)
703 {
704 if (depths[calleeIndex] == currentDepth - 1)
705 {
706 currentDepth--;
707 nextFunction = calleeIndex;
708 }
709 }
710
711 currentFunction = nextFunction;
712 }
713
714 return false;
715 }
716 }
717
718 return true;
719}
720
721bool TCompiler::tagUsedFunctions()
722{
723 // Search from main, starting from the end of the DAG as it usually is the root.
Cooper Partin4d61f7e2015-08-12 10:56:50 -0700724 for (size_t i = mCallDag.size(); i-- > 0;)
Corentin Wallez71d147f2015-02-11 11:15:24 -0800725 {
726 if (mCallDag.getRecordFromIndex(i).name == "main(")
727 {
728 internalTagUsedFunction(i);
729 return true;
730 }
731 }
732
733 infoSink.info.prefix(EPrefixError);
Olli Etuaho792a41d2015-12-15 12:39:16 +0200734 infoSink.info << "Missing main()\n";
Corentin Wallez71d147f2015-02-11 11:15:24 -0800735 return false;
736}
737
738void TCompiler::internalTagUsedFunction(size_t index)
739{
740 if (functionMetadata[index].used)
741 {
742 return;
743 }
744
745 functionMetadata[index].used = true;
746
747 for (int calleeIndex : mCallDag.getRecordFromIndex(index).callees)
748 {
749 internalTagUsedFunction(calleeIndex);
zmo@google.comb1762df2011-07-30 02:04:23 +0000750 }
751}
752
Corentin Walleza094a8a2015-04-07 11:53:06 -0700753// A predicate for the stl that returns if a top-level node is unused
754class TCompiler::UnusedPredicate
755{
756 public:
757 UnusedPredicate(const CallDAG *callDag, const std::vector<FunctionMetadata> *metadatas)
758 : mCallDag(callDag),
759 mMetadatas(metadatas)
760 {
761 }
762
763 bool operator ()(TIntermNode *node)
764 {
765 const TIntermAggregate *asAggregate = node->getAsAggregate();
766
767 if (asAggregate == nullptr)
768 {
769 return false;
770 }
771
772 if (!(asAggregate->getOp() == EOpFunction || asAggregate->getOp() == EOpPrototype))
773 {
774 return false;
775 }
776
Olli Etuahobd674552016-10-06 13:28:42 +0100777 size_t callDagIndex = mCallDag->findIndex(asAggregate->getFunctionSymbolInfo());
Corentin Walleza094a8a2015-04-07 11:53:06 -0700778 if (callDagIndex == CallDAG::InvalidIndex)
779 {
780 // This happens only for unimplemented prototypes which are thus unused
781 ASSERT(asAggregate->getOp() == EOpPrototype);
782 return true;
783 }
784
785 ASSERT(callDagIndex < mMetadatas->size());
786 return !(*mMetadatas)[callDagIndex].used;
787 }
788
789 private:
790 const CallDAG *mCallDag;
791 const std::vector<FunctionMetadata> *mMetadatas;
792};
793
Olli Etuaho6d40bbd2016-09-30 13:49:38 +0100794bool TCompiler::pruneUnusedFunctions(TIntermBlock *root)
Corentin Walleza094a8a2015-04-07 11:53:06 -0700795{
Corentin Walleza094a8a2015-04-07 11:53:06 -0700796 UnusedPredicate isUnused(&mCallDag, &functionMetadata);
Olli Etuaho6d40bbd2016-09-30 13:49:38 +0100797 TIntermSequence *sequence = root->getSequence();
Corentin Wallezb081e782015-07-20 05:40:04 -0700798
799 if (!sequence->empty())
800 {
801 sequence->erase(std::remove_if(sequence->begin(), sequence->end(), isUnused), sequence->end());
802 }
Corentin Walleza094a8a2015-04-07 11:53:06 -0700803
804 return true;
805}
806
Jamie Madill05a80ce2013-06-20 11:55:49 -0400807bool TCompiler::validateOutputs(TIntermNode* root)
808{
Kimmo Kinnunenb18609b2015-07-16 14:13:11 +0300809 ValidateOutputs validateOutputs(getExtensionBehavior(), compileResources.MaxDrawBuffers);
Jamie Madill05a80ce2013-06-20 11:55:49 -0400810 root->traverse(&validateOutputs);
Kimmo Kinnunenb18609b2015-07-16 14:13:11 +0300811 return (validateOutputs.validateAndCountErrors(infoSink.info) == 0);
Jamie Madill05a80ce2013-06-20 11:55:49 -0400812}
813
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800814bool TCompiler::validateLimitations(TIntermNode* root)
815{
Olli Etuaho8a76dcc2015-12-10 20:25:12 +0200816 ValidateLimitations validate(shaderType, &infoSink.info);
alokp@chromium.orgb59a7782010-11-24 18:38:33 +0000817 root->traverse(&validate);
818 return validate.numErrors() == 0;
819}
820
Jamie Madilleb1a0102013-07-08 13:31:38 -0400821bool TCompiler::limitExpressionComplexity(TIntermNode* root)
822{
Jamie Madill6654bc92014-03-26 14:01:57 -0400823 TMaxDepthTraverser traverser(maxExpressionComplexity+1);
Jamie Madilleb1a0102013-07-08 13:31:38 -0400824 root->traverse(&traverser);
Jamie Madill6654bc92014-03-26 14:01:57 -0400825
826 if (traverser.getMaxDepth() > maxExpressionComplexity)
827 {
828 infoSink.info << "Expression too complex.";
829 return false;
830 }
831
Olli Etuaho19d1dc92016-03-08 17:18:46 +0200832 if (!ValidateMaxParameters::validate(root, maxFunctionParameters))
833 {
834 infoSink.info << "Function has too many parameters.";
835 return false;
836 }
837
Jamie Madilleb1a0102013-07-08 13:31:38 -0400838 return true;
839}
840
Zhenyao Mo74da9f22013-09-23 14:57:01 -0400841void TCompiler::collectVariables(TIntermNode* root)
alokp@chromium.org07620a52010-09-23 17:53:56 +0000842{
Kenneth Russellbccc65d2016-07-19 16:48:43 -0700843 if (!variablesCollected)
844 {
845 sh::CollectVariables collect(&attributes, &outputVariables, &uniforms, &varyings,
846 &interfaceBlocks, hashFunction, symbolTable, extensionBehavior);
847 root->traverse(&collect);
Jamie Madill23a8a432014-07-09 13:27:42 -0400848
Kenneth Russellbccc65d2016-07-19 16:48:43 -0700849 // This is for enforcePackingRestriction().
850 sh::ExpandUniforms(uniforms, &expandedUniforms);
851 variablesCollected = true;
852 }
alokp@chromium.org07620a52010-09-23 17:53:56 +0000853}
zmo@google.comfd747b82011-04-23 01:30:07 +0000854
gman@chromium.org8d804792012-10-17 21:33:48 +0000855bool TCompiler::enforcePackingRestrictions()
856{
857 VariablePacker packer;
Jamie Madill23a8a432014-07-09 13:27:42 -0400858 return packer.CheckVariablesWithinPackingLimits(maxUniformVectors, expandedUniforms);
gman@chromium.org8d804792012-10-17 21:33:48 +0000859}
860
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800861void TCompiler::initializeGLPosition(TIntermNode* root)
862{
Zhenyao Mo72111912016-07-20 17:45:56 -0700863 InitVariableList list;
864 sh::ShaderVariable var(GL_FLOAT_VEC4, 0);
865 var.name = "gl_Position";
866 list.push_back(var);
867 InitializeVariables(root, list);
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800868}
869
Qin Jiajia7835b522016-10-08 11:20:17 +0800870void TCompiler::useAllMembersInUnusedStandardAndSharedBlocks(TIntermNode *root)
871{
872 sh::InterfaceBlockList list;
873
874 for (auto block : interfaceBlocks)
875 {
876 if (!block.staticUse &&
877 (block.layout == sh::BLOCKLAYOUT_STANDARD || block.layout == sh::BLOCKLAYOUT_SHARED))
878 {
879 list.push_back(block);
880 }
881 }
882
883 sh::UseInterfaceBlockFields(root, list);
884}
885
Olli Etuaho27776e32016-07-22 14:00:56 +0300886void TCompiler::initializeOutputVariables(TIntermNode *root)
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800887{
Zhenyao Mo72111912016-07-20 17:45:56 -0700888 InitVariableList list;
889 if (shaderType == GL_VERTEX_SHADER)
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800890 {
Zhenyao Mo72111912016-07-20 17:45:56 -0700891 for (auto var : varyings)
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800892 {
Zhenyao Mof9312682016-07-22 12:51:31 -0700893 list.push_back(var);
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800894 }
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800895 }
Zhenyao Mo72111912016-07-20 17:45:56 -0700896 else
897 {
898 ASSERT(shaderType == GL_FRAGMENT_SHADER);
899 for (auto var : outputVariables)
900 {
901 list.push_back(var);
902 }
903 }
904 InitializeVariables(root, list);
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800905}
906
zmo@google.com5601ea02011-06-10 18:23:25 +0000907const TExtensionBehavior& TCompiler::getExtensionBehavior() const
908{
909 return extensionBehavior;
910}
zmo@google.com32e97312011-08-24 01:03:11 +0000911
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200912const char *TCompiler::getSourcePath() const
913{
914 return mSourcePath;
915}
916
shannon.woods%transgaming.com@gtempaccount.com18b4c4b2013-04-13 03:31:40 +0000917const ShBuiltInResources& TCompiler::getResources() const
918{
919 return compileResources;
920}
921
daniel@transgaming.com4167cc92013-01-11 04:11:53 +0000922const ArrayBoundsClamper& TCompiler::getArrayBoundsClamper() const
923{
924 return arrayBoundsClamper;
925}
926
shannon.woods@transgaming.com1d432bb2013-01-25 21:57:28 +0000927ShArrayIndexClampingStrategy TCompiler::getArrayIndexClampingStrategy() const
928{
929 return clampingStrategy;
930}
931
Olli Etuaho8efc5ad2015-03-03 17:21:10 +0200932const BuiltInFunctionEmulator& TCompiler::getBuiltInFunctionEmulator() const
shannon.woods@transgaming.com1d432bb2013-01-25 21:57:28 +0000933{
934 return builtInFunctionEmulator;
935}
Zhenyao Mo94ac7b72014-10-15 18:22:08 -0700936
Qiankun Miao7ebb97f2016-09-08 18:01:50 +0800937void TCompiler::writePragma(ShCompileOptions compileOptions)
Zhenyao Mo94ac7b72014-10-15 18:22:08 -0700938{
Kenneth Russellbccc65d2016-07-19 16:48:43 -0700939 if (!(compileOptions & SH_FLATTEN_PRAGMA_STDGL_INVARIANT_ALL))
940 {
941 TInfoSinkBase &sink = infoSink.obj;
942 if (mPragma.stdgl.invariantAll)
943 sink << "#pragma STDGL invariant(all)\n";
944 }
945}
946
947bool TCompiler::isVaryingDefined(const char *varyingName)
948{
949 ASSERT(variablesCollected);
950 for (size_t ii = 0; ii < varyings.size(); ++ii)
951 {
952 if (varyings[ii].name == varyingName)
953 {
954 return true;
955 }
956 }
957
958 return false;
Zhenyao Mo94ac7b72014-10-15 18:22:08 -0700959}