blob: 0fab6f82376d35a06fde526bab93e3d07638cc78 [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"
Geoff Lang17732822013-08-29 13:46:49 -040030#include "compiler/translator/ValidateLimitations.h"
Olli Etuaho19d1dc92016-03-08 17:18:46 +020031#include "compiler/translator/ValidateMaxParameters.h"
Geoff Lang17732822013-08-29 13:46:49 -040032#include "compiler/translator/ValidateOutputs.h"
33#include "compiler/translator/VariablePacker.h"
shannon.woods@transgaming.comda1ed362013-01-25 21:54:57 +000034#include "third_party/compiler/ArrayBoundsClamper.h"
Corentin Wallez28b65282016-06-16 07:24:50 -070035
36namespace
37{
38
39#if defined(ANGLE_ENABLE_FUZZER_CORPUS_OUTPUT)
40void DumpFuzzerCase(char const *const *shaderStrings,
41 size_t numStrings,
42 uint32_t type,
43 uint32_t spec,
44 uint32_t output,
45 uint64_t options)
46{
47 static int fileIndex = 0;
48
49 std::ostringstream o;
50 o << "corpus/" << fileIndex++ << ".sample";
51 std::string s = o.str();
52
53 // Must match the input format of the fuzzer
54 FILE *f = fopen(s.c_str(), "w");
55 fwrite(&type, sizeof(type), 1, f);
56 fwrite(&spec, sizeof(spec), 1, f);
57 fwrite(&output, sizeof(output), 1, f);
58 fwrite(&options, sizeof(options), 1, f);
59
60 char zero[128 - 20] = {0};
61 fwrite(&zero, 128 - 20, 1, f);
62
63 for (size_t i = 0; i < numStrings; i++)
64 {
65 fwrite(shaderStrings[i], sizeof(char), strlen(shaderStrings[i]), f);
66 }
67 fwrite(&zero, 1, 1, f);
68
69 fclose(f);
70}
71#endif // defined(ANGLE_ENABLE_FUZZER_CORPUS_OUTPUT)
72} // anonymous namespace
73
Jamie Madill5508f392014-02-20 13:31:36 -050074bool IsWebGLBasedSpec(ShShaderSpec spec)
maxvujovic@gmail.com430f5e02012-06-08 17:47:59 +000075{
Qiankun Miaoc2c5fc42016-08-31 15:24:22 +080076 return (spec == SH_WEBGL_SPEC || spec == SH_WEBGL2_SPEC || spec == SH_WEBGL3_SPEC);
maxvujovic@gmail.com430f5e02012-06-08 17:47:59 +000077}
78
Qingqing Dengad0d0792015-04-08 14:25:06 -070079bool IsGLSL130OrNewer(ShShaderOutput output)
80{
81 return (output == SH_GLSL_130_OUTPUT ||
Geoff Lang8273e002015-06-15 13:40:19 -070082 output == SH_GLSL_140_OUTPUT ||
83 output == SH_GLSL_150_CORE_OUTPUT ||
84 output == SH_GLSL_330_CORE_OUTPUT ||
85 output == SH_GLSL_400_CORE_OUTPUT ||
Qingqing Dengad0d0792015-04-08 14:25:06 -070086 output == SH_GLSL_410_CORE_OUTPUT ||
Geoff Lang8273e002015-06-15 13:40:19 -070087 output == SH_GLSL_420_CORE_OUTPUT ||
88 output == SH_GLSL_430_CORE_OUTPUT ||
89 output == SH_GLSL_440_CORE_OUTPUT ||
90 output == SH_GLSL_450_CORE_OUTPUT);
Qingqing Dengad0d0792015-04-08 14:25:06 -070091}
92
Zhenyao Mo7faf1a12014-04-25 18:03:56 -070093size_t GetGlobalMaxTokenSize(ShShaderSpec spec)
Jamie Madill88f6e942014-02-19 10:27:53 -050094{
Jamie Madill88f6e942014-02-19 10:27:53 -050095 // WebGL defines a max token legnth of 256, while ES2 leaves max token
96 // size undefined. ES3 defines a max size of 1024 characters.
Zhenyao Modb9b40b2014-10-29 15:00:04 -070097 switch (spec)
Jamie Madill88f6e942014-02-19 10:27:53 -050098 {
Zhenyao Modb9b40b2014-10-29 15:00:04 -070099 case SH_WEBGL_SPEC:
Jamie Madill88f6e942014-02-19 10:27:53 -0500100 return 256;
Zhenyao Modb9b40b2014-10-29 15:00:04 -0700101 default:
Jamie Madill88f6e942014-02-19 10:27:53 -0500102 return 1024;
103 }
104}
105
alokp@chromium.orgbafcbaa2010-11-23 19:07:43 +0000106namespace {
Zhenyao Modb9b40b2014-10-29 15:00:04 -0700107
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800108class TScopedPoolAllocator
109{
110 public:
111 TScopedPoolAllocator(TPoolAllocator* allocator) : mAllocator(allocator)
112 {
Alok Priyadarshibc3f1ac2013-09-23 14:57:02 -0400113 mAllocator->push();
alokp@chromium.orgbafcbaa2010-11-23 19:07:43 +0000114 SetGlobalPoolAllocator(mAllocator);
115 }
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800116 ~TScopedPoolAllocator()
117 {
alokp@chromium.orgbafcbaa2010-11-23 19:07:43 +0000118 SetGlobalPoolAllocator(NULL);
Alok Priyadarshibc3f1ac2013-09-23 14:57:02 -0400119 mAllocator->pop();
alokp@chromium.orgbafcbaa2010-11-23 19:07:43 +0000120 }
121
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800122 private:
alokp@chromium.orgbafcbaa2010-11-23 19:07:43 +0000123 TPoolAllocator* mAllocator;
Alok Priyadarshibc3f1ac2013-09-23 14:57:02 -0400124};
125
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800126class TScopedSymbolTableLevel
127{
128 public:
129 TScopedSymbolTableLevel(TSymbolTable* table) : mTable(table)
130 {
Alok Priyadarshibc3f1ac2013-09-23 14:57:02 -0400131 ASSERT(mTable->atBuiltInLevel());
132 mTable->push();
133 }
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800134 ~TScopedSymbolTableLevel()
135 {
Alok Priyadarshibc3f1ac2013-09-23 14:57:02 -0400136 while (!mTable->atBuiltInLevel())
137 mTable->pop();
138 }
139
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800140 private:
Alok Priyadarshibc3f1ac2013-09-23 14:57:02 -0400141 TSymbolTable* mTable;
alokp@chromium.orgbafcbaa2010-11-23 19:07:43 +0000142};
Zhenyao Modb9b40b2014-10-29 15:00:04 -0700143
144int MapSpecToShaderVersion(ShShaderSpec spec)
145{
146 switch (spec)
147 {
148 case SH_GLES2_SPEC:
149 case SH_WEBGL_SPEC:
Zhenyao Modb9b40b2014-10-29 15:00:04 -0700150 return 100;
151 case SH_GLES3_SPEC:
152 case SH_WEBGL2_SPEC:
153 return 300;
Martin Radev1be913c2016-07-11 17:59:16 +0300154 case SH_GLES3_1_SPEC:
155 case SH_WEBGL3_SPEC:
156 return 310;
Zhenyao Modb9b40b2014-10-29 15:00:04 -0700157 default:
158 UNREACHABLE();
159 return 0;
160 }
161}
162
alokp@chromium.orgbafcbaa2010-11-23 19:07:43 +0000163} // namespace
164
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800165TShHandleBase::TShHandleBase()
166{
alokp@chromium.orgbafcbaa2010-11-23 19:07:43 +0000167 allocator.push();
168 SetGlobalPoolAllocator(&allocator);
169}
170
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800171TShHandleBase::~TShHandleBase()
172{
alokp@chromium.orgbafcbaa2010-11-23 19:07:43 +0000173 SetGlobalPoolAllocator(NULL);
174 allocator.popAll();
175}
176
Jamie Madill183bde52014-07-02 15:31:19 -0400177TCompiler::TCompiler(sh::GLenum type, ShShaderSpec spec, ShShaderOutput output)
Kenneth Russellbccc65d2016-07-19 16:48:43 -0700178 : variablesCollected(false),
179 shaderType(type),
zmo@google.comf420c422011-09-12 18:27:59 +0000180 shaderSpec(spec),
Jamie Madill68fe74a2014-05-27 12:56:01 -0400181 outputType(output),
Jamie Madilleb1a0102013-07-08 13:31:38 -0400182 maxUniformVectors(0),
183 maxExpressionComplexity(0),
184 maxCallStackDepth(0),
Olli Etuaho19d1dc92016-03-08 17:18:46 +0200185 maxFunctionParameters(0),
shannon.woods%transgaming.com@gtempaccount.comcbb6b6a2013-04-13 03:27:47 +0000186 fragmentPrecisionHigh(false),
shannon.woods@transgaming.com1d432bb2013-01-25 21:57:28 +0000187 clampingStrategy(SH_CLAMP_WITH_CLAMP_INTRINSIC),
Olli Etuaho8efc5ad2015-03-03 17:21:10 +0200188 builtInFunctionEmulator(),
Corentin Wallezd4b50542015-09-28 12:19:26 -0700189 mSourcePath(NULL),
Martin Radev802abe02016-08-04 17:48:32 +0300190 mComputeShaderLocalSizeDeclared(false),
Corentin Wallezd4b50542015-09-28 12:19:26 -0700191 mTemporaryIndex(0)
alokp@chromium.org4888ceb2010-10-01 21:13:12 +0000192{
Martin Radev802abe02016-08-04 17:48:32 +0300193 mComputeShaderLocalSize.fill(1);
alokp@chromium.org4888ceb2010-10-01 21:13:12 +0000194}
195
196TCompiler::~TCompiler()
197{
198}
199
Qiankun Miao7ebb97f2016-09-08 18:01:50 +0800200bool TCompiler::shouldRunLoopAndIndexingValidation(ShCompileOptions compileOptions) const
Olli Etuaho5d91dda2015-06-18 15:47:46 +0300201{
202 // If compiling an ESSL 1.00 shader for WebGL, or if its been requested through the API,
203 // validate loop and indexing as well (to verify that the shader only uses minimal functionality
204 // of ESSL 1.00 as in Appendix A of the spec).
205 return (IsWebGLBasedSpec(shaderSpec) && shaderVersion == 100) ||
206 (compileOptions & SH_VALIDATE_LOOP_INDEXING);
207}
208
alokp@chromium.org4888ceb2010-10-01 21:13:12 +0000209bool TCompiler::Init(const ShBuiltInResources& resources)
alokp@chromium.org07620a52010-09-23 17:53:56 +0000210{
shannon.woods%transgaming.com@gtempaccount.com0bbed382013-04-13 03:38:07 +0000211 shaderVersion = 100;
Jamie Madill183bde52014-07-02 15:31:19 -0400212 maxUniformVectors = (shaderType == GL_VERTEX_SHADER) ?
gman@chromium.org8d804792012-10-17 21:33:48 +0000213 resources.MaxVertexUniformVectors :
214 resources.MaxFragmentUniformVectors;
Jamie Madilleb1a0102013-07-08 13:31:38 -0400215 maxExpressionComplexity = resources.MaxExpressionComplexity;
Olli Etuaho19d1dc92016-03-08 17:18:46 +0200216 maxCallStackDepth = resources.MaxCallStackDepth;
217 maxFunctionParameters = resources.MaxFunctionParameters;
Alok Priyadarshibc3f1ac2013-09-23 14:57:02 -0400218
219 SetGlobalPoolAllocator(&allocator);
alokp@chromium.orgbafcbaa2010-11-23 19:07:43 +0000220
alokp@chromium.org07620a52010-09-23 17:53:56 +0000221 // Generate built-in symbol table.
222 if (!InitBuiltInSymbolTable(resources))
223 return false;
alokp@chromium.org07620a52010-09-23 17:53:56 +0000224 InitExtensionBehavior(resources, extensionBehavior);
shannon.woods%transgaming.com@gtempaccount.comcbb6b6a2013-04-13 03:27:47 +0000225 fragmentPrecisionHigh = resources.FragmentPrecisionHigh == 1;
alokp@chromium.orgbafcbaa2010-11-23 19:07:43 +0000226
shannon.woods@transgaming.com1d432bb2013-01-25 21:57:28 +0000227 arrayBoundsClamper.SetClampingStrategy(resources.ArrayIndexClampingStrategy);
228 clampingStrategy = resources.ArrayIndexClampingStrategy;
229
daniel@transgaming.comc23f4612012-11-28 19:42:57 +0000230 hashFunction = resources.HashFunction;
231
alokp@chromium.org07620a52010-09-23 17:53:56 +0000232 return true;
233}
234
Olli Etuaho6d40bbd2016-09-30 13:49:38 +0100235TIntermBlock *TCompiler::compileTreeForTesting(const char *const shaderStrings[],
236 size_t numStrings,
237 ShCompileOptions compileOptions)
alokp@chromium.org07620a52010-09-23 17:53:56 +0000238{
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200239 return compileTreeImpl(shaderStrings, numStrings, compileOptions);
240}
241
Olli Etuaho6d40bbd2016-09-30 13:49:38 +0100242TIntermBlock *TCompiler::compileTreeImpl(const char *const shaderStrings[],
243 size_t numStrings,
244 const ShCompileOptions compileOptions)
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200245{
alokp@chromium.org07620a52010-09-23 17:53:56 +0000246 clearResults();
247
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200248 ASSERT(numStrings > 0);
249 ASSERT(GetGlobalPoolAllocator());
alokp@chromium.org07620a52010-09-23 17:53:56 +0000250
David Yen0fbd1282015-02-02 14:46:09 -0800251 // Reset the extension behavior for each compilation unit.
252 ResetExtensionBehavior(extensionBehavior);
253
apatrick@chromium.org0f4cefe2011-01-26 19:30:57 +0000254 // First string is path of source file if flag is set. The actual source follows.
shannon.woods@transgaming.comd64b3da2013-02-28 23:19:26 +0000255 size_t firstSource = 0;
apatrick@chromium.org0f4cefe2011-01-26 19:30:57 +0000256 if (compileOptions & SH_SOURCE_PATH)
257 {
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200258 mSourcePath = shaderStrings[0];
apatrick@chromium.org0f4cefe2011-01-26 19:30:57 +0000259 ++firstSource;
260 }
261
Olli Etuahof119a262016-08-19 15:54:22 +0300262 TParseContext parseContext(symbolTable, extensionBehavior, shaderType, shaderSpec,
Olli Etuahoe1a94c62015-11-16 17:35:25 +0200263 compileOptions, true, infoSink, getResources());
Olli Etuaho853dc1a2014-11-06 17:25:48 +0200264
Olli Etuahoa6996682015-10-12 14:32:30 +0300265 parseContext.setFragmentPrecisionHighOnESSL1(fragmentPrecisionHigh);
Alok Priyadarshi8156b6b2013-09-23 14:56:58 -0400266 SetGlobalParseContext(&parseContext);
alokp@chromium.org07620a52010-09-23 17:53:56 +0000267
268 // We preserve symbols at the built-in level from compile-to-compile.
269 // Start pushing the user-defined symbols at global level.
Alok Priyadarshibc3f1ac2013-09-23 14:57:02 -0400270 TScopedSymbolTableLevel scopedSymbolLevel(&symbolTable);
alokp@chromium.org07620a52010-09-23 17:53:56 +0000271
272 // Parse shader.
273 bool success =
Jamie Madill6e06b1f2015-05-14 10:01:17 -0400274 (PaParseStrings(numStrings - firstSource, &shaderStrings[firstSource], nullptr, &parseContext) == 0) &&
275 (parseContext.getTreeRoot() != nullptr);
shannon.woods%transgaming.com@gtempaccount.com0bbed382013-04-13 03:38:07 +0000276
shannon.woods%transgaming.com@gtempaccount.com5524db02013-04-13 03:38:16 +0000277 shaderVersion = parseContext.getShaderVersion();
Zhenyao Modb9b40b2014-10-29 15:00:04 -0700278 if (success && MapSpecToShaderVersion(shaderSpec) < shaderVersion)
279 {
280 infoSink.info.prefix(EPrefixError);
281 infoSink.info << "unsupported shader version";
282 success = false;
283 }
shannon.woods%transgaming.com@gtempaccount.com0bbed382013-04-13 03:38:07 +0000284
Olli Etuaho6d40bbd2016-09-30 13:49:38 +0100285 TIntermBlock *root = nullptr;
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200286
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800287 if (success)
288 {
Zhenyao Mo94ac7b72014-10-15 18:22:08 -0700289 mPragma = parseContext.pragma();
Kenneth Russell8bad46d2016-07-01 19:52:52 -0700290 symbolTable.setGlobalInvariant(mPragma.stdgl.invariantAll);
Zhenyao Mo94ac7b72014-10-15 18:22:08 -0700291
Martin Radev802abe02016-08-04 17:48:32 +0300292 mComputeShaderLocalSizeDeclared = parseContext.isComputeShaderLocalSizeDeclared();
293 mComputeShaderLocalSize = parseContext.getComputeShaderLocalSize();
294
Jamie Madill6e06b1f2015-05-14 10:01:17 -0400295 root = parseContext.getTreeRoot();
alokp@chromium.orgb59a7782010-11-24 18:38:33 +0000296
Olli Etuahoa6996682015-10-12 14:32:30 +0300297 // Highp might have been auto-enabled based on shader version
298 fragmentPrecisionHigh = parseContext.getFragmentPrecisionHigh();
299
Jamie Madill6654bc92014-03-26 14:01:57 -0400300 // Disallow expressions deemed too complex.
301 if (success && (compileOptions & SH_LIMIT_EXPRESSION_COMPLEXITY))
302 success = limitExpressionComplexity(root);
303
Corentin Wallez71d147f2015-02-11 11:15:24 -0800304 // Create the function DAG and check there is no recursion
zmo@google.comb1762df2011-07-30 02:04:23 +0000305 if (success)
Corentin Wallez71d147f2015-02-11 11:15:24 -0800306 success = initCallDag(root);
307
308 if (success && (compileOptions & SH_LIMIT_CALL_STACK_DEPTH))
309 success = checkCallDepth();
310
311 // Checks which functions are used and if "main" exists
312 if (success)
313 {
314 functionMetadata.clear();
315 functionMetadata.resize(mCallDag.size());
316 success = tagUsedFunctions();
317 }
zmo@google.comb1762df2011-07-30 02:04:23 +0000318
Corentin Walleza094a8a2015-04-07 11:53:06 -0700319 if (success && !(compileOptions & SH_DONT_PRUNE_UNUSED_FUNCTIONS))
320 success = pruneUnusedFunctions(root);
321
Olli Etuahoc6833112015-04-22 15:15:54 +0300322 // Prune empty declarations to work around driver bugs and to keep declaration output simple.
323 if (success)
324 PruneEmptyDeclarations(root);
325
Jamie Madill183bde52014-07-02 15:31:19 -0400326 if (success && shaderVersion == 300 && shaderType == GL_FRAGMENT_SHADER)
Jamie Madill05a80ce2013-06-20 11:55:49 -0400327 success = validateOutputs(root);
328
Olli Etuaho5d91dda2015-06-18 15:47:46 +0300329 if (success && shouldRunLoopAndIndexingValidation(compileOptions))
alokp@chromium.orgb59a7782010-11-24 18:38:33 +0000330 success = validateLimitations(root);
alokp@chromium.org07620a52010-09-23 17:53:56 +0000331
Jamie Madilld5696192016-10-06 11:09:24 -0400332 // Fail compilation if precision emulation not supported.
333 if (success && getResources().WEBGL_debug_shader_precision &&
334 getPragma().debugShaderPrecision)
335 {
336 if (!EmulatePrecision::SupportedInLanguage(outputType))
337 {
338 infoSink.info.prefix(EPrefixError);
339 infoSink.info << "Precision emulation not supported for this output type.";
340 success = false;
341 }
342 }
343
zmo@google.com0c6bb7a2011-08-17 19:39:58 +0000344 // Unroll for-loop markup needs to happen after validateLimitations pass.
345 if (success && (compileOptions & SH_UNROLL_FOR_LOOP_WITH_INTEGER_INDEX))
Zhenyao Mo3cdfcce2014-03-07 13:00:08 -0800346 {
Olli Etuaho8a76dcc2015-12-10 20:25:12 +0200347 ForLoopUnrollMarker marker(ForLoopUnrollMarker::kIntegerIndex,
348 shouldRunLoopAndIndexingValidation(compileOptions));
Zhenyao Mo550c6002014-02-26 15:40:48 -0800349 root->traverse(&marker);
350 }
351 if (success && (compileOptions & SH_UNROLL_FOR_LOOP_WITH_SAMPLER_ARRAY_INDEX))
Zhenyao Mo3cdfcce2014-03-07 13:00:08 -0800352 {
Olli Etuaho8a76dcc2015-12-10 20:25:12 +0200353 ForLoopUnrollMarker marker(ForLoopUnrollMarker::kSamplerArrayIndex,
354 shouldRunLoopAndIndexingValidation(compileOptions));
Zhenyao Mo550c6002014-02-26 15:40:48 -0800355 root->traverse(&marker);
356 if (marker.samplerArrayIndexIsFloatLoopIndex())
357 {
358 infoSink.info.prefix(EPrefixError);
359 infoSink.info << "sampler array index is float loop index";
360 success = false;
361 }
362 }
zmo@google.com0c6bb7a2011-08-17 19:39:58 +0000363
zmo@google.com32e97312011-08-24 01:03:11 +0000364 // Built-in function emulation needs to happen after validateLimitations pass.
Olli Etuaho8efc5ad2015-03-03 17:21:10 +0200365 if (success)
366 {
Jamie Madill438dbcf2016-06-17 14:20:05 -0400367 // TODO(jmadill): Remove global pool allocator.
368 GetGlobalPoolAllocator()->lock();
Olli Etuaho8efc5ad2015-03-03 17:21:10 +0200369 initBuiltInFunctionEmulator(&builtInFunctionEmulator, compileOptions);
Jamie Madill438dbcf2016-06-17 14:20:05 -0400370 GetGlobalPoolAllocator()->unlock();
zmo@google.com32e97312011-08-24 01:03:11 +0000371 builtInFunctionEmulator.MarkBuiltInFunctionsForEmulation(root);
Olli Etuaho8efc5ad2015-03-03 17:21:10 +0200372 }
zmo@google.com32e97312011-08-24 01:03:11 +0000373
daniel@transgaming.com4167cc92013-01-11 04:11:53 +0000374 // Clamping uniform array bounds needs to happen after validateLimitations pass.
375 if (success && (compileOptions & SH_CLAMP_INDIRECT_ARRAY_BOUNDS))
376 arrayBoundsClamper.MarkIndirectArrayBoundsForClamping(root);
377
Ian Ewell924b7de2016-01-21 13:54:28 -0500378 // gl_Position is always written in compatibility output mode
379 if (success && shaderType == GL_VERTEX_SHADER &&
380 ((compileOptions & SH_INIT_GL_POSITION) ||
381 (outputType == SH_GLSL_COMPATIBILITY_OUTPUT)))
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800382 initializeGLPosition(root);
Zhenyao Moac44cd22013-09-23 14:57:09 -0400383
Corentin Wallezd4b50542015-09-28 12:19:26 -0700384 // This pass might emit short circuits so keep it before the short circuit unfolding
385 if (success && (compileOptions & SH_REWRITE_DO_WHILE_LOOPS))
386 RewriteDoWhile(root, getTemporaryIndex());
387
Qiankun Miao09cfac62016-09-06 17:25:16 +0800388 if (success && (compileOptions & SH_ADD_AND_TRUE_TO_LOOP_CONDITION))
389 sh::AddAndTrueToLoopCondition(root);
390
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800391 if (success && (compileOptions & SH_UNFOLD_SHORT_CIRCUIT))
392 {
Zhenyao Mo7cab38b2013-10-15 12:59:30 -0700393 UnfoldShortCircuitAST unfoldShortCircuit;
394 root->traverse(&unfoldShortCircuit);
395 unfoldShortCircuit.updateTree();
396 }
397
Olli Etuaho5c407bb2015-06-01 12:20:39 +0300398 if (success && (compileOptions & SH_REMOVE_POW_WITH_CONSTANT_EXPONENT))
399 {
400 RemovePow(root);
401 }
402
Olli Etuaho4dfe8092015-08-21 17:44:35 +0300403 if (success && shouldCollectVariables(compileOptions))
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800404 {
Zhenyao Mo74da9f22013-09-23 14:57:01 -0400405 collectVariables(root);
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800406 if (compileOptions & SH_ENFORCE_PACKING_RESTRICTIONS)
407 {
gman@chromium.org8d804792012-10-17 21:33:48 +0000408 success = enforcePackingRestrictions();
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800409 if (!success)
410 {
Jamie Madill075edd82013-07-08 13:30:19 -0400411 infoSink.info.prefix(EPrefixError);
412 infoSink.info << "too many uniforms";
gman@chromium.org8d804792012-10-17 21:33:48 +0000413 }
414 }
Zhenyao Mo72111912016-07-20 17:45:56 -0700415 if (success && (compileOptions & SH_INIT_OUTPUT_VARIABLES))
416 {
Olli Etuaho27776e32016-07-22 14:00:56 +0300417 initializeOutputVariables(root);
Zhenyao Mo72111912016-07-20 17:45:56 -0700418 }
gman@chromium.org8d804792012-10-17 21:33:48 +0000419 }
zmo@google.comfd747b82011-04-23 01:30:07 +0000420
Zhenyao Mocd68fe72014-07-11 10:45:44 -0700421 if (success && (compileOptions & SH_SCALARIZE_VEC_AND_MAT_CONSTRUCTOR_ARGS))
422 {
Zhenyao Modaf56572014-08-06 16:18:30 -0700423 ScalarizeVecAndMatConstructorArgs scalarizer(
424 shaderType, fragmentPrecisionHigh);
Zhenyao Mocd68fe72014-07-11 10:45:44 -0700425 root->traverse(&scalarizer);
426 }
427
Zhenyao Moe740add2014-07-18 17:01:01 -0700428 if (success && (compileOptions & SH_REGENERATE_STRUCT_NAMES))
429 {
430 RegenerateStructNames gen(symbolTable, shaderVersion);
431 root->traverse(&gen);
432 }
Olli Etuaho3d932d82016-04-12 11:10:30 +0300433
Zhenyao Mo4e94fea2016-08-09 14:31:37 -0700434 if (success && shaderType == GL_FRAGMENT_SHADER && shaderVersion == 100 &&
435 compileResources.EXT_draw_buffers && compileResources.MaxDrawBuffers > 1 &&
436 IsExtensionEnabled(extensionBehavior, "GL_EXT_draw_buffers"))
437 {
438 EmulateGLFragColorBroadcast(root, compileResources.MaxDrawBuffers, &outputVariables);
439 }
440
Olli Etuaho3d932d82016-04-12 11:10:30 +0300441 if (success)
442 {
443 DeferGlobalInitializers(root);
444 }
alokp@chromium.org07620a52010-09-23 17:53:56 +0000445 }
446
Zhenyao Mo7faf1a12014-04-25 18:03:56 -0700447 SetGlobalParseContext(NULL);
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200448 if (success)
449 return root;
450
451 return NULL;
452}
453
Qiankun Miao7ebb97f2016-09-08 18:01:50 +0800454bool TCompiler::compile(const char *const shaderStrings[],
455 size_t numStrings,
456 ShCompileOptions compileOptionsIn)
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200457{
Corentin Wallez28b65282016-06-16 07:24:50 -0700458#if defined(ANGLE_ENABLE_FUZZER_CORPUS_OUTPUT)
459 DumpFuzzerCase(shaderStrings, numStrings, shaderType, shaderSpec, outputType, compileOptionsIn);
460#endif // defined(ANGLE_ENABLE_FUZZER_CORPUS_OUTPUT)
461
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200462 if (numStrings == 0)
463 return true;
464
Qiankun Miao7ebb97f2016-09-08 18:01:50 +0800465 ShCompileOptions compileOptions = compileOptionsIn;
Kenneth Russellbccc65d2016-07-19 16:48:43 -0700466
467 // Apply key workarounds.
468 if (shouldFlattenPragmaStdglInvariantAll())
469 {
470 // This should be harmless to do in all cases, but for the moment, do it only conditionally.
471 compileOptions |= SH_FLATTEN_PRAGMA_STDGL_INVARIANT_ALL;
472 }
473
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200474 TScopedPoolAllocator scopedAlloc(&allocator);
Olli Etuaho6d40bbd2016-09-30 13:49:38 +0100475 TIntermBlock *root = compileTreeImpl(shaderStrings, numStrings, compileOptions);
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200476
477 if (root)
478 {
479 if (compileOptions & SH_INTERMEDIATE_TREE)
480 TIntermediate::outputTree(root, infoSink.info);
481
482 if (compileOptions & SH_OBJECT_CODE)
483 translate(root, compileOptions);
484
485 // The IntermNode tree doesn't need to be deleted here, since the
486 // memory will be freed in a big chunk by the PoolAllocator.
487 return true;
488 }
489 return false;
alokp@chromium.org07620a52010-09-23 17:53:56 +0000490}
491
Nicolas Capens49a88872013-06-20 09:54:03 -0400492bool TCompiler::InitBuiltInSymbolTable(const ShBuiltInResources &resources)
alokp@chromium.org07620a52010-09-23 17:53:56 +0000493{
shannon.woods%transgaming.com@gtempaccount.com18b4c4b2013-04-13 03:31:40 +0000494 compileResources = resources;
Shannon Woods2d76e5f2014-05-16 17:46:41 -0400495 setResourceString();
shannonwoods@chromium.org2ac0be92013-05-30 00:02:27 +0000496
Nicolas Capens49a88872013-06-20 09:54:03 -0400497 assert(symbolTable.isEmpty());
498 symbolTable.push(); // COMMON_BUILTINS
499 symbolTable.push(); // ESSL1_BUILTINS
500 symbolTable.push(); // ESSL3_BUILTINS
Martin Radeve93d24e2016-07-28 12:06:05 +0300501 symbolTable.push(); // ESSL3_1_BUILTINS
shannonwoods@chromium.org2ac0be92013-05-30 00:02:27 +0000502
Nicolas Capens49a88872013-06-20 09:54:03 -0400503 TPublicType integer;
Martin Radev4a9cd802016-09-01 16:51:51 +0300504 integer.setBasicType(EbtInt);
505 integer.initializeSizeForScalarTypes();
Nicolas Capens49a88872013-06-20 09:54:03 -0400506 integer.array = false;
507
508 TPublicType floatingPoint;
Martin Radev4a9cd802016-09-01 16:51:51 +0300509 floatingPoint.setBasicType(EbtFloat);
510 floatingPoint.initializeSizeForScalarTypes();
Nicolas Capens49a88872013-06-20 09:54:03 -0400511 floatingPoint.array = false;
512
513 switch(shaderType)
514 {
Jamie Madill183bde52014-07-02 15:31:19 -0400515 case GL_FRAGMENT_SHADER:
Nicolas Capens49a88872013-06-20 09:54:03 -0400516 symbolTable.setDefaultPrecision(integer, EbpMedium);
517 break;
Jamie Madill183bde52014-07-02 15:31:19 -0400518 case GL_VERTEX_SHADER:
Nicolas Capens49a88872013-06-20 09:54:03 -0400519 symbolTable.setDefaultPrecision(integer, EbpHigh);
520 symbolTable.setDefaultPrecision(floatingPoint, EbpHigh);
521 break;
Martin Radev802abe02016-08-04 17:48:32 +0300522 case GL_COMPUTE_SHADER:
523 symbolTable.setDefaultPrecision(integer, EbpHigh);
524 symbolTable.setDefaultPrecision(floatingPoint, EbpHigh);
525 break;
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800526 default:
527 assert(false && "Language not supported");
Nicolas Capens49a88872013-06-20 09:54:03 -0400528 }
Olli Etuaho183d7e22015-11-20 15:59:09 +0200529 // Set defaults for sampler types that have default precision, even those that are
Zhenyao Moa5a1dfc2013-09-23 14:57:03 -0400530 // only available if an extension exists.
Olli Etuaho183d7e22015-11-20 15:59:09 +0200531 // New sampler types in ESSL3 don't have default precision. ESSL1 types do.
532 initSamplerDefaultPrecision(EbtSampler2D);
533 initSamplerDefaultPrecision(EbtSamplerCube);
534 // SamplerExternalOES is specified in the extension to have default precision.
535 initSamplerDefaultPrecision(EbtSamplerExternalOES);
536 // It isn't specified whether Sampler2DRect has default precision.
537 initSamplerDefaultPrecision(EbtSampler2DRect);
Nicolas Capens49a88872013-06-20 09:54:03 -0400538
Jamie Madill1b452142013-07-12 14:51:11 -0400539 InsertBuiltInFunctions(shaderType, shaderSpec, resources, symbolTable);
Nicolas Capens49a88872013-06-20 09:54:03 -0400540
541 IdentifyBuiltIns(shaderType, shaderSpec, resources, symbolTable);
542
543 return true;
alokp@chromium.org07620a52010-09-23 17:53:56 +0000544}
545
Olli Etuaho183d7e22015-11-20 15:59:09 +0200546void TCompiler::initSamplerDefaultPrecision(TBasicType samplerType)
547{
548 ASSERT(samplerType > EbtGuardSamplerBegin && samplerType < EbtGuardSamplerEnd);
549 TPublicType sampler;
Martin Radev4a9cd802016-09-01 16:51:51 +0300550 sampler.initializeSizeForScalarTypes();
551 sampler.setBasicType(samplerType);
Olli Etuaho183d7e22015-11-20 15:59:09 +0200552 sampler.array = false;
Olli Etuaho183d7e22015-11-20 15:59:09 +0200553 symbolTable.setDefaultPrecision(sampler, EbpLow);
554}
555
Shannon Woods2d76e5f2014-05-16 17:46:41 -0400556void TCompiler::setResourceString()
557{
558 std::ostringstream strstream;
Geoff Langb66a9092016-05-16 15:59:14 -0400559
560 // clang-format off
Shannon Woods2d76e5f2014-05-16 17:46:41 -0400561 strstream << ":MaxVertexAttribs:" << compileResources.MaxVertexAttribs
562 << ":MaxVertexUniformVectors:" << compileResources.MaxVertexUniformVectors
563 << ":MaxVaryingVectors:" << compileResources.MaxVaryingVectors
564 << ":MaxVertexTextureImageUnits:" << compileResources.MaxVertexTextureImageUnits
565 << ":MaxCombinedTextureImageUnits:" << compileResources.MaxCombinedTextureImageUnits
566 << ":MaxTextureImageUnits:" << compileResources.MaxTextureImageUnits
567 << ":MaxFragmentUniformVectors:" << compileResources.MaxFragmentUniformVectors
568 << ":MaxDrawBuffers:" << compileResources.MaxDrawBuffers
569 << ":OES_standard_derivatives:" << compileResources.OES_standard_derivatives
570 << ":OES_EGL_image_external:" << compileResources.OES_EGL_image_external
Geoff Langb66a9092016-05-16 15:59:14 -0400571 << ":OES_EGL_image_external_essl3:" << compileResources.OES_EGL_image_external_essl3
572 << ":NV_EGL_stream_consumer_external:" << compileResources.NV_EGL_stream_consumer_external
Shannon Woods2d76e5f2014-05-16 17:46:41 -0400573 << ":ARB_texture_rectangle:" << compileResources.ARB_texture_rectangle
574 << ":EXT_draw_buffers:" << compileResources.EXT_draw_buffers
575 << ":FragmentPrecisionHigh:" << compileResources.FragmentPrecisionHigh
576 << ":MaxExpressionComplexity:" << compileResources.MaxExpressionComplexity
577 << ":MaxCallStackDepth:" << compileResources.MaxCallStackDepth
Olli Etuaho19d1dc92016-03-08 17:18:46 +0200578 << ":MaxFunctionParameters:" << compileResources.MaxFunctionParameters
Kimmo Kinnunenb18609b2015-07-16 14:13:11 +0300579 << ":EXT_blend_func_extended:" << compileResources.EXT_blend_func_extended
Shannon Woods2d76e5f2014-05-16 17:46:41 -0400580 << ":EXT_frag_depth:" << compileResources.EXT_frag_depth
581 << ":EXT_shader_texture_lod:" << compileResources.EXT_shader_texture_lod
Erik Dahlströmea7a2122014-11-17 16:15:57 +0100582 << ":EXT_shader_framebuffer_fetch:" << compileResources.EXT_shader_framebuffer_fetch
583 << ":NV_shader_framebuffer_fetch:" << compileResources.NV_shader_framebuffer_fetch
584 << ":ARM_shader_framebuffer_fetch:" << compileResources.ARM_shader_framebuffer_fetch
Shannon Woods2d76e5f2014-05-16 17:46:41 -0400585 << ":MaxVertexOutputVectors:" << compileResources.MaxVertexOutputVectors
586 << ":MaxFragmentInputVectors:" << compileResources.MaxFragmentInputVectors
587 << ":MinProgramTexelOffset:" << compileResources.MinProgramTexelOffset
Olli Etuahoe61209a2014-09-26 12:01:17 +0300588 << ":MaxProgramTexelOffset:" << compileResources.MaxProgramTexelOffset
Kimmo Kinnunenb18609b2015-07-16 14:13:11 +0300589 << ":MaxDualSourceDrawBuffers:" << compileResources.MaxDualSourceDrawBuffers
Olli Etuaho853dc1a2014-11-06 17:25:48 +0200590 << ":NV_draw_buffers:" << compileResources.NV_draw_buffers
Martin Radeve93d24e2016-07-28 12:06:05 +0300591 << ":WEBGL_debug_shader_precision:" << compileResources.WEBGL_debug_shader_precision
592 << ":MaxImageUnits:" << compileResources.MaxImageUnits
593 << ":MaxVertexImageUniforms:" << compileResources.MaxVertexImageUniforms
594 << ":MaxFragmentImageUniforms:" << compileResources.MaxFragmentImageUniforms
595 << ":MaxComputeImageUniforms:" << compileResources.MaxComputeImageUniforms
596 << ":MaxCombinedImageUniforms:" << compileResources.MaxCombinedImageUniforms
597 << ":MaxCombinedShaderOutputResources:" << compileResources.MaxCombinedShaderOutputResources
598 << ":MaxComputeWorkGroupCountX:" << compileResources.MaxComputeWorkGroupCount[0]
599 << ":MaxComputeWorkGroupCountY:" << compileResources.MaxComputeWorkGroupCount[1]
600 << ":MaxComputeWorkGroupCountZ:" << compileResources.MaxComputeWorkGroupCount[2]
601 << ":MaxComputeWorkGroupSizeX:" << compileResources.MaxComputeWorkGroupSize[0]
602 << ":MaxComputeWorkGroupSizeY:" << compileResources.MaxComputeWorkGroupSize[1]
603 << ":MaxComputeWorkGroupSizeZ:" << compileResources.MaxComputeWorkGroupSize[2]
604 << ":MaxComputeUniformComponents:" << compileResources.MaxComputeUniformComponents
605 << ":MaxComputeTextureImageUnits:" << compileResources.MaxComputeTextureImageUnits
606 << ":MaxComputeAtomicCounters:" << compileResources.MaxComputeAtomicCounters
607 << ":MaxComputeAtomicCounterBuffers:" << compileResources.MaxComputeAtomicCounterBuffers
608 << ":MaxVertexAtomicCounters:" << compileResources.MaxVertexAtomicCounters
609 << ":MaxFragmentAtomicCounters:" << compileResources.MaxFragmentAtomicCounters
610 << ":MaxCombinedAtomicCounters:" << compileResources.MaxCombinedAtomicCounters
611 << ":MaxAtomicCounterBindings:" << compileResources.MaxAtomicCounterBindings
612 << ":MaxVertexAtomicCounterBuffers:" << compileResources.MaxVertexAtomicCounterBuffers
613 << ":MaxFragmentAtomicCounterBuffers:" << compileResources.MaxFragmentAtomicCounterBuffers
614 << ":MaxCombinedAtomicCounterBuffers:" << compileResources.MaxCombinedAtomicCounterBuffers
615 << ":MaxAtomicCounterBufferSize:" << compileResources.MaxAtomicCounterBufferSize;
Geoff Langb66a9092016-05-16 15:59:14 -0400616 // clang-format on
Shannon Woods2d76e5f2014-05-16 17:46:41 -0400617
618 builtInResourcesString = strstream.str();
619}
620
alokp@chromium.org07620a52010-09-23 17:53:56 +0000621void TCompiler::clearResults()
622{
daniel@transgaming.com4167cc92013-01-11 04:11:53 +0000623 arrayBoundsClamper.Cleanup();
alokp@chromium.org07620a52010-09-23 17:53:56 +0000624 infoSink.info.erase();
625 infoSink.obj.erase();
626 infoSink.debug.erase();
627
Jamie Madilled27c722014-07-02 15:31:23 -0400628 attributes.clear();
629 outputVariables.clear();
alokp@chromium.org07620a52010-09-23 17:53:56 +0000630 uniforms.clear();
Jamie Madill23a8a432014-07-09 13:27:42 -0400631 expandedUniforms.clear();
Zhenyao Mod2d340b2013-09-23 14:57:05 -0400632 varyings.clear();
Jamie Madilled27c722014-07-02 15:31:23 -0400633 interfaceBlocks.clear();
Kenneth Russellbccc65d2016-07-19 16:48:43 -0700634 variablesCollected = false;
zmo@google.coma3b4ab42011-09-16 00:53:26 +0000635
636 builtInFunctionEmulator.Cleanup();
daniel@transgaming.com0aa3b5a2012-11-28 19:43:24 +0000637
638 nameMap.clear();
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200639
640 mSourcePath = NULL;
Corentin Wallezd4b50542015-09-28 12:19:26 -0700641 mTemporaryIndex = 0;
alokp@chromium.org07620a52010-09-23 17:53:56 +0000642}
643
Corentin Wallez71d147f2015-02-11 11:15:24 -0800644bool TCompiler::initCallDag(TIntermNode *root)
zmo@google.comb1762df2011-07-30 02:04:23 +0000645{
Corentin Wallez71d147f2015-02-11 11:15:24 -0800646 mCallDag.clear();
647
648 switch (mCallDag.init(root, &infoSink.info))
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800649 {
Corentin Wallez71d147f2015-02-11 11:15:24 -0800650 case CallDAG::INITDAG_SUCCESS:
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800651 return true;
Corentin Wallez71d147f2015-02-11 11:15:24 -0800652 case CallDAG::INITDAG_RECURSION:
653 infoSink.info.prefix(EPrefixError);
654 infoSink.info << "Function recursion detected";
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800655 return false;
Corentin Wallez71d147f2015-02-11 11:15:24 -0800656 case CallDAG::INITDAG_UNDEFINED:
657 infoSink.info.prefix(EPrefixError);
658 infoSink.info << "Unimplemented function detected";
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800659 return false;
Corentin Wallez71d147f2015-02-11 11:15:24 -0800660 }
661
662 UNREACHABLE();
663 return true;
664}
665
666bool TCompiler::checkCallDepth()
667{
668 std::vector<int> depths(mCallDag.size());
669
670 for (size_t i = 0; i < mCallDag.size(); i++)
671 {
672 int depth = 0;
673 auto &record = mCallDag.getRecordFromIndex(i);
674
675 for (auto &calleeIndex : record.callees)
676 {
677 depth = std::max(depth, depths[calleeIndex] + 1);
678 }
679
680 depths[i] = depth;
681
682 if (depth >= maxCallStackDepth)
683 {
684 // Trace back the function chain to have a meaningful info log.
685 infoSink.info.prefix(EPrefixError);
686 infoSink.info << "Call stack too deep (larger than " << maxCallStackDepth
687 << ") with the following call chain: " << record.name;
688
Cooper Partin4d61f7e2015-08-12 10:56:50 -0700689 int currentFunction = static_cast<int>(i);
Corentin Wallez71d147f2015-02-11 11:15:24 -0800690 int currentDepth = depth;
691
692 while (currentFunction != -1)
693 {
694 infoSink.info << " -> " << mCallDag.getRecordFromIndex(currentFunction).name;
695
696 int nextFunction = -1;
697 for (auto& calleeIndex : mCallDag.getRecordFromIndex(currentFunction).callees)
698 {
699 if (depths[calleeIndex] == currentDepth - 1)
700 {
701 currentDepth--;
702 nextFunction = calleeIndex;
703 }
704 }
705
706 currentFunction = nextFunction;
707 }
708
709 return false;
710 }
711 }
712
713 return true;
714}
715
716bool TCompiler::tagUsedFunctions()
717{
718 // Search from main, starting from the end of the DAG as it usually is the root.
Cooper Partin4d61f7e2015-08-12 10:56:50 -0700719 for (size_t i = mCallDag.size(); i-- > 0;)
Corentin Wallez71d147f2015-02-11 11:15:24 -0800720 {
721 if (mCallDag.getRecordFromIndex(i).name == "main(")
722 {
723 internalTagUsedFunction(i);
724 return true;
725 }
726 }
727
728 infoSink.info.prefix(EPrefixError);
Olli Etuaho792a41d2015-12-15 12:39:16 +0200729 infoSink.info << "Missing main()\n";
Corentin Wallez71d147f2015-02-11 11:15:24 -0800730 return false;
731}
732
733void TCompiler::internalTagUsedFunction(size_t index)
734{
735 if (functionMetadata[index].used)
736 {
737 return;
738 }
739
740 functionMetadata[index].used = true;
741
742 for (int calleeIndex : mCallDag.getRecordFromIndex(index).callees)
743 {
744 internalTagUsedFunction(calleeIndex);
zmo@google.comb1762df2011-07-30 02:04:23 +0000745 }
746}
747
Corentin Walleza094a8a2015-04-07 11:53:06 -0700748// A predicate for the stl that returns if a top-level node is unused
749class TCompiler::UnusedPredicate
750{
751 public:
752 UnusedPredicate(const CallDAG *callDag, const std::vector<FunctionMetadata> *metadatas)
753 : mCallDag(callDag),
754 mMetadatas(metadatas)
755 {
756 }
757
758 bool operator ()(TIntermNode *node)
759 {
760 const TIntermAggregate *asAggregate = node->getAsAggregate();
761
762 if (asAggregate == nullptr)
763 {
764 return false;
765 }
766
767 if (!(asAggregate->getOp() == EOpFunction || asAggregate->getOp() == EOpPrototype))
768 {
769 return false;
770 }
771
Olli Etuahobd674552016-10-06 13:28:42 +0100772 size_t callDagIndex = mCallDag->findIndex(asAggregate->getFunctionSymbolInfo());
Corentin Walleza094a8a2015-04-07 11:53:06 -0700773 if (callDagIndex == CallDAG::InvalidIndex)
774 {
775 // This happens only for unimplemented prototypes which are thus unused
776 ASSERT(asAggregate->getOp() == EOpPrototype);
777 return true;
778 }
779
780 ASSERT(callDagIndex < mMetadatas->size());
781 return !(*mMetadatas)[callDagIndex].used;
782 }
783
784 private:
785 const CallDAG *mCallDag;
786 const std::vector<FunctionMetadata> *mMetadatas;
787};
788
Olli Etuaho6d40bbd2016-09-30 13:49:38 +0100789bool TCompiler::pruneUnusedFunctions(TIntermBlock *root)
Corentin Walleza094a8a2015-04-07 11:53:06 -0700790{
Corentin Walleza094a8a2015-04-07 11:53:06 -0700791 UnusedPredicate isUnused(&mCallDag, &functionMetadata);
Olli Etuaho6d40bbd2016-09-30 13:49:38 +0100792 TIntermSequence *sequence = root->getSequence();
Corentin Wallezb081e782015-07-20 05:40:04 -0700793
794 if (!sequence->empty())
795 {
796 sequence->erase(std::remove_if(sequence->begin(), sequence->end(), isUnused), sequence->end());
797 }
Corentin Walleza094a8a2015-04-07 11:53:06 -0700798
799 return true;
800}
801
Jamie Madill05a80ce2013-06-20 11:55:49 -0400802bool TCompiler::validateOutputs(TIntermNode* root)
803{
Kimmo Kinnunenb18609b2015-07-16 14:13:11 +0300804 ValidateOutputs validateOutputs(getExtensionBehavior(), compileResources.MaxDrawBuffers);
Jamie Madill05a80ce2013-06-20 11:55:49 -0400805 root->traverse(&validateOutputs);
Kimmo Kinnunenb18609b2015-07-16 14:13:11 +0300806 return (validateOutputs.validateAndCountErrors(infoSink.info) == 0);
Jamie Madill05a80ce2013-06-20 11:55:49 -0400807}
808
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800809bool TCompiler::validateLimitations(TIntermNode* root)
810{
Olli Etuaho8a76dcc2015-12-10 20:25:12 +0200811 ValidateLimitations validate(shaderType, &infoSink.info);
alokp@chromium.orgb59a7782010-11-24 18:38:33 +0000812 root->traverse(&validate);
813 return validate.numErrors() == 0;
814}
815
Jamie Madilleb1a0102013-07-08 13:31:38 -0400816bool TCompiler::limitExpressionComplexity(TIntermNode* root)
817{
Jamie Madill6654bc92014-03-26 14:01:57 -0400818 TMaxDepthTraverser traverser(maxExpressionComplexity+1);
Jamie Madilleb1a0102013-07-08 13:31:38 -0400819 root->traverse(&traverser);
Jamie Madill6654bc92014-03-26 14:01:57 -0400820
821 if (traverser.getMaxDepth() > maxExpressionComplexity)
822 {
823 infoSink.info << "Expression too complex.";
824 return false;
825 }
826
Olli Etuaho19d1dc92016-03-08 17:18:46 +0200827 if (!ValidateMaxParameters::validate(root, maxFunctionParameters))
828 {
829 infoSink.info << "Function has too many parameters.";
830 return false;
831 }
832
Jamie Madilleb1a0102013-07-08 13:31:38 -0400833 return true;
834}
835
Zhenyao Mo74da9f22013-09-23 14:57:01 -0400836void TCompiler::collectVariables(TIntermNode* root)
alokp@chromium.org07620a52010-09-23 17:53:56 +0000837{
Kenneth Russellbccc65d2016-07-19 16:48:43 -0700838 if (!variablesCollected)
839 {
840 sh::CollectVariables collect(&attributes, &outputVariables, &uniforms, &varyings,
841 &interfaceBlocks, hashFunction, symbolTable, extensionBehavior);
842 root->traverse(&collect);
Jamie Madill23a8a432014-07-09 13:27:42 -0400843
Kenneth Russellbccc65d2016-07-19 16:48:43 -0700844 // This is for enforcePackingRestriction().
845 sh::ExpandUniforms(uniforms, &expandedUniforms);
846 variablesCollected = true;
847 }
alokp@chromium.org07620a52010-09-23 17:53:56 +0000848}
zmo@google.comfd747b82011-04-23 01:30:07 +0000849
gman@chromium.org8d804792012-10-17 21:33:48 +0000850bool TCompiler::enforcePackingRestrictions()
851{
852 VariablePacker packer;
Jamie Madill23a8a432014-07-09 13:27:42 -0400853 return packer.CheckVariablesWithinPackingLimits(maxUniformVectors, expandedUniforms);
gman@chromium.org8d804792012-10-17 21:33:48 +0000854}
855
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800856void TCompiler::initializeGLPosition(TIntermNode* root)
857{
Zhenyao Mo72111912016-07-20 17:45:56 -0700858 InitVariableList list;
859 sh::ShaderVariable var(GL_FLOAT_VEC4, 0);
860 var.name = "gl_Position";
861 list.push_back(var);
862 InitializeVariables(root, list);
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800863}
864
Olli Etuaho27776e32016-07-22 14:00:56 +0300865void TCompiler::initializeOutputVariables(TIntermNode *root)
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800866{
Zhenyao Mo72111912016-07-20 17:45:56 -0700867 InitVariableList list;
868 if (shaderType == GL_VERTEX_SHADER)
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800869 {
Zhenyao Mo72111912016-07-20 17:45:56 -0700870 for (auto var : varyings)
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800871 {
Zhenyao Mof9312682016-07-22 12:51:31 -0700872 list.push_back(var);
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800873 }
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800874 }
Zhenyao Mo72111912016-07-20 17:45:56 -0700875 else
876 {
877 ASSERT(shaderType == GL_FRAGMENT_SHADER);
878 for (auto var : outputVariables)
879 {
880 list.push_back(var);
881 }
882 }
883 InitializeVariables(root, list);
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800884}
885
zmo@google.com5601ea02011-06-10 18:23:25 +0000886const TExtensionBehavior& TCompiler::getExtensionBehavior() const
887{
888 return extensionBehavior;
889}
zmo@google.com32e97312011-08-24 01:03:11 +0000890
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200891const char *TCompiler::getSourcePath() const
892{
893 return mSourcePath;
894}
895
shannon.woods%transgaming.com@gtempaccount.com18b4c4b2013-04-13 03:31:40 +0000896const ShBuiltInResources& TCompiler::getResources() const
897{
898 return compileResources;
899}
900
daniel@transgaming.com4167cc92013-01-11 04:11:53 +0000901const ArrayBoundsClamper& TCompiler::getArrayBoundsClamper() const
902{
903 return arrayBoundsClamper;
904}
905
shannon.woods@transgaming.com1d432bb2013-01-25 21:57:28 +0000906ShArrayIndexClampingStrategy TCompiler::getArrayIndexClampingStrategy() const
907{
908 return clampingStrategy;
909}
910
Olli Etuaho8efc5ad2015-03-03 17:21:10 +0200911const BuiltInFunctionEmulator& TCompiler::getBuiltInFunctionEmulator() const
shannon.woods@transgaming.com1d432bb2013-01-25 21:57:28 +0000912{
913 return builtInFunctionEmulator;
914}
Zhenyao Mo94ac7b72014-10-15 18:22:08 -0700915
Qiankun Miao7ebb97f2016-09-08 18:01:50 +0800916void TCompiler::writePragma(ShCompileOptions compileOptions)
Zhenyao Mo94ac7b72014-10-15 18:22:08 -0700917{
Kenneth Russellbccc65d2016-07-19 16:48:43 -0700918 if (!(compileOptions & SH_FLATTEN_PRAGMA_STDGL_INVARIANT_ALL))
919 {
920 TInfoSinkBase &sink = infoSink.obj;
921 if (mPragma.stdgl.invariantAll)
922 sink << "#pragma STDGL invariant(all)\n";
923 }
924}
925
926bool TCompiler::isVaryingDefined(const char *varyingName)
927{
928 ASSERT(variablesCollected);
929 for (size_t ii = 0; ii < varyings.size(); ++ii)
930 {
931 if (varyings[ii].name == varyingName)
932 {
933 return true;
934 }
935 }
936
937 return false;
Zhenyao Mo94ac7b72014-10-15 18:22:08 -0700938}