blob: 6c8a9d6125ad68c6b5afdf9d712abe3173a8fd7c [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"
Qiankun Miao705a9192016-08-29 10:05:27 +080026#include "compiler/translator/RemoveInvariantDeclaration.h"
Olli Etuaho5c407bb2015-06-01 12:20:39 +030027#include "compiler/translator/RemovePow.h"
Corentin Wallezd4b50542015-09-28 12:19:26 -070028#include "compiler/translator/RewriteDoWhile.h"
Zhenyao Mocd68fe72014-07-11 10:45:44 -070029#include "compiler/translator/ScalarizeVecAndMatConstructorArgs.h"
Zhenyao Mo7cab38b2013-10-15 12:59:30 -070030#include "compiler/translator/UnfoldShortCircuitAST.h"
Qin Jiajia7835b522016-10-08 11:20:17 +080031#include "compiler/translator/UseInterfaceBlockFields.h"
Geoff Lang17732822013-08-29 13:46:49 -040032#include "compiler/translator/ValidateLimitations.h"
Olli Etuaho19d1dc92016-03-08 17:18:46 +020033#include "compiler/translator/ValidateMaxParameters.h"
Geoff Lang17732822013-08-29 13:46:49 -040034#include "compiler/translator/ValidateOutputs.h"
35#include "compiler/translator/VariablePacker.h"
shannon.woods@transgaming.comda1ed362013-01-25 21:54:57 +000036#include "third_party/compiler/ArrayBoundsClamper.h"
Corentin Wallez28b65282016-06-16 07:24:50 -070037
38namespace
39{
40
41#if defined(ANGLE_ENABLE_FUZZER_CORPUS_OUTPUT)
42void DumpFuzzerCase(char const *const *shaderStrings,
43 size_t numStrings,
44 uint32_t type,
45 uint32_t spec,
46 uint32_t output,
47 uint64_t options)
48{
49 static int fileIndex = 0;
50
51 std::ostringstream o;
52 o << "corpus/" << fileIndex++ << ".sample";
53 std::string s = o.str();
54
55 // Must match the input format of the fuzzer
56 FILE *f = fopen(s.c_str(), "w");
57 fwrite(&type, sizeof(type), 1, f);
58 fwrite(&spec, sizeof(spec), 1, f);
59 fwrite(&output, sizeof(output), 1, f);
60 fwrite(&options, sizeof(options), 1, f);
61
62 char zero[128 - 20] = {0};
63 fwrite(&zero, 128 - 20, 1, f);
64
65 for (size_t i = 0; i < numStrings; i++)
66 {
67 fwrite(shaderStrings[i], sizeof(char), strlen(shaderStrings[i]), f);
68 }
69 fwrite(&zero, 1, 1, f);
70
71 fclose(f);
72}
73#endif // defined(ANGLE_ENABLE_FUZZER_CORPUS_OUTPUT)
74} // anonymous namespace
75
Jamie Madill5508f392014-02-20 13:31:36 -050076bool IsWebGLBasedSpec(ShShaderSpec spec)
maxvujovic@gmail.com430f5e02012-06-08 17:47:59 +000077{
Qiankun Miaoc2c5fc42016-08-31 15:24:22 +080078 return (spec == SH_WEBGL_SPEC || spec == SH_WEBGL2_SPEC || spec == SH_WEBGL3_SPEC);
maxvujovic@gmail.com430f5e02012-06-08 17:47:59 +000079}
80
Qingqing Dengad0d0792015-04-08 14:25:06 -070081bool IsGLSL130OrNewer(ShShaderOutput output)
82{
83 return (output == SH_GLSL_130_OUTPUT ||
Geoff Lang8273e002015-06-15 13:40:19 -070084 output == SH_GLSL_140_OUTPUT ||
85 output == SH_GLSL_150_CORE_OUTPUT ||
86 output == SH_GLSL_330_CORE_OUTPUT ||
87 output == SH_GLSL_400_CORE_OUTPUT ||
Qingqing Dengad0d0792015-04-08 14:25:06 -070088 output == SH_GLSL_410_CORE_OUTPUT ||
Geoff Lang8273e002015-06-15 13:40:19 -070089 output == SH_GLSL_420_CORE_OUTPUT ||
90 output == SH_GLSL_430_CORE_OUTPUT ||
91 output == SH_GLSL_440_CORE_OUTPUT ||
92 output == SH_GLSL_450_CORE_OUTPUT);
Qingqing Dengad0d0792015-04-08 14:25:06 -070093}
94
Qiankun Miao705a9192016-08-29 10:05:27 +080095bool IsGLSL420OrNewer(ShShaderOutput output)
96{
97 return (output == SH_GLSL_420_CORE_OUTPUT ||
98 output == SH_GLSL_430_CORE_OUTPUT ||
99 output == SH_GLSL_440_CORE_OUTPUT ||
100 output == SH_GLSL_450_CORE_OUTPUT);
101}
102
Zhenyao Mo7faf1a12014-04-25 18:03:56 -0700103size_t GetGlobalMaxTokenSize(ShShaderSpec spec)
Jamie Madill88f6e942014-02-19 10:27:53 -0500104{
Jamie Madill88f6e942014-02-19 10:27:53 -0500105 // WebGL defines a max token legnth of 256, while ES2 leaves max token
106 // size undefined. ES3 defines a max size of 1024 characters.
Zhenyao Modb9b40b2014-10-29 15:00:04 -0700107 switch (spec)
Jamie Madill88f6e942014-02-19 10:27:53 -0500108 {
Zhenyao Modb9b40b2014-10-29 15:00:04 -0700109 case SH_WEBGL_SPEC:
Jamie Madill88f6e942014-02-19 10:27:53 -0500110 return 256;
Zhenyao Modb9b40b2014-10-29 15:00:04 -0700111 default:
Jamie Madill88f6e942014-02-19 10:27:53 -0500112 return 1024;
113 }
114}
115
alokp@chromium.orgbafcbaa2010-11-23 19:07:43 +0000116namespace {
Zhenyao Modb9b40b2014-10-29 15:00:04 -0700117
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800118class TScopedPoolAllocator
119{
120 public:
121 TScopedPoolAllocator(TPoolAllocator* allocator) : mAllocator(allocator)
122 {
Alok Priyadarshibc3f1ac2013-09-23 14:57:02 -0400123 mAllocator->push();
alokp@chromium.orgbafcbaa2010-11-23 19:07:43 +0000124 SetGlobalPoolAllocator(mAllocator);
125 }
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800126 ~TScopedPoolAllocator()
127 {
alokp@chromium.orgbafcbaa2010-11-23 19:07:43 +0000128 SetGlobalPoolAllocator(NULL);
Alok Priyadarshibc3f1ac2013-09-23 14:57:02 -0400129 mAllocator->pop();
alokp@chromium.orgbafcbaa2010-11-23 19:07:43 +0000130 }
131
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800132 private:
alokp@chromium.orgbafcbaa2010-11-23 19:07:43 +0000133 TPoolAllocator* mAllocator;
Alok Priyadarshibc3f1ac2013-09-23 14:57:02 -0400134};
135
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800136class TScopedSymbolTableLevel
137{
138 public:
139 TScopedSymbolTableLevel(TSymbolTable* table) : mTable(table)
140 {
Alok Priyadarshibc3f1ac2013-09-23 14:57:02 -0400141 ASSERT(mTable->atBuiltInLevel());
142 mTable->push();
143 }
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800144 ~TScopedSymbolTableLevel()
145 {
Alok Priyadarshibc3f1ac2013-09-23 14:57:02 -0400146 while (!mTable->atBuiltInLevel())
147 mTable->pop();
148 }
149
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800150 private:
Alok Priyadarshibc3f1ac2013-09-23 14:57:02 -0400151 TSymbolTable* mTable;
alokp@chromium.orgbafcbaa2010-11-23 19:07:43 +0000152};
Zhenyao Modb9b40b2014-10-29 15:00:04 -0700153
154int MapSpecToShaderVersion(ShShaderSpec spec)
155{
156 switch (spec)
157 {
158 case SH_GLES2_SPEC:
159 case SH_WEBGL_SPEC:
Zhenyao Modb9b40b2014-10-29 15:00:04 -0700160 return 100;
161 case SH_GLES3_SPEC:
162 case SH_WEBGL2_SPEC:
163 return 300;
Martin Radev1be913c2016-07-11 17:59:16 +0300164 case SH_GLES3_1_SPEC:
165 case SH_WEBGL3_SPEC:
166 return 310;
Zhenyao Modb9b40b2014-10-29 15:00:04 -0700167 default:
168 UNREACHABLE();
169 return 0;
170 }
171}
172
alokp@chromium.orgbafcbaa2010-11-23 19:07:43 +0000173} // namespace
174
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800175TShHandleBase::TShHandleBase()
176{
alokp@chromium.orgbafcbaa2010-11-23 19:07:43 +0000177 allocator.push();
178 SetGlobalPoolAllocator(&allocator);
179}
180
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800181TShHandleBase::~TShHandleBase()
182{
alokp@chromium.orgbafcbaa2010-11-23 19:07:43 +0000183 SetGlobalPoolAllocator(NULL);
184 allocator.popAll();
185}
186
Jamie Madill183bde52014-07-02 15:31:19 -0400187TCompiler::TCompiler(sh::GLenum type, ShShaderSpec spec, ShShaderOutput output)
Kenneth Russellbccc65d2016-07-19 16:48:43 -0700188 : variablesCollected(false),
189 shaderType(type),
zmo@google.comf420c422011-09-12 18:27:59 +0000190 shaderSpec(spec),
Jamie Madill68fe74a2014-05-27 12:56:01 -0400191 outputType(output),
Jamie Madilleb1a0102013-07-08 13:31:38 -0400192 maxUniformVectors(0),
193 maxExpressionComplexity(0),
194 maxCallStackDepth(0),
Olli Etuaho19d1dc92016-03-08 17:18:46 +0200195 maxFunctionParameters(0),
shannon.woods%transgaming.com@gtempaccount.comcbb6b6a2013-04-13 03:27:47 +0000196 fragmentPrecisionHigh(false),
shannon.woods@transgaming.com1d432bb2013-01-25 21:57:28 +0000197 clampingStrategy(SH_CLAMP_WITH_CLAMP_INTRINSIC),
Olli Etuaho8efc5ad2015-03-03 17:21:10 +0200198 builtInFunctionEmulator(),
Corentin Wallezd4b50542015-09-28 12:19:26 -0700199 mSourcePath(NULL),
Martin Radev802abe02016-08-04 17:48:32 +0300200 mComputeShaderLocalSizeDeclared(false),
Corentin Wallezd4b50542015-09-28 12:19:26 -0700201 mTemporaryIndex(0)
alokp@chromium.org4888ceb2010-10-01 21:13:12 +0000202{
Martin Radev802abe02016-08-04 17:48:32 +0300203 mComputeShaderLocalSize.fill(1);
alokp@chromium.org4888ceb2010-10-01 21:13:12 +0000204}
205
206TCompiler::~TCompiler()
207{
208}
209
Qiankun Miao7ebb97f2016-09-08 18:01:50 +0800210bool TCompiler::shouldRunLoopAndIndexingValidation(ShCompileOptions compileOptions) const
Olli Etuaho5d91dda2015-06-18 15:47:46 +0300211{
212 // If compiling an ESSL 1.00 shader for WebGL, or if its been requested through the API,
213 // validate loop and indexing as well (to verify that the shader only uses minimal functionality
214 // of ESSL 1.00 as in Appendix A of the spec).
215 return (IsWebGLBasedSpec(shaderSpec) && shaderVersion == 100) ||
216 (compileOptions & SH_VALIDATE_LOOP_INDEXING);
217}
218
alokp@chromium.org4888ceb2010-10-01 21:13:12 +0000219bool TCompiler::Init(const ShBuiltInResources& resources)
alokp@chromium.org07620a52010-09-23 17:53:56 +0000220{
shannon.woods%transgaming.com@gtempaccount.com0bbed382013-04-13 03:38:07 +0000221 shaderVersion = 100;
Jamie Madill183bde52014-07-02 15:31:19 -0400222 maxUniformVectors = (shaderType == GL_VERTEX_SHADER) ?
gman@chromium.org8d804792012-10-17 21:33:48 +0000223 resources.MaxVertexUniformVectors :
224 resources.MaxFragmentUniformVectors;
Jamie Madilleb1a0102013-07-08 13:31:38 -0400225 maxExpressionComplexity = resources.MaxExpressionComplexity;
Olli Etuaho19d1dc92016-03-08 17:18:46 +0200226 maxCallStackDepth = resources.MaxCallStackDepth;
227 maxFunctionParameters = resources.MaxFunctionParameters;
Alok Priyadarshibc3f1ac2013-09-23 14:57:02 -0400228
229 SetGlobalPoolAllocator(&allocator);
alokp@chromium.orgbafcbaa2010-11-23 19:07:43 +0000230
alokp@chromium.org07620a52010-09-23 17:53:56 +0000231 // Generate built-in symbol table.
232 if (!InitBuiltInSymbolTable(resources))
233 return false;
alokp@chromium.org07620a52010-09-23 17:53:56 +0000234 InitExtensionBehavior(resources, extensionBehavior);
shannon.woods%transgaming.com@gtempaccount.comcbb6b6a2013-04-13 03:27:47 +0000235 fragmentPrecisionHigh = resources.FragmentPrecisionHigh == 1;
alokp@chromium.orgbafcbaa2010-11-23 19:07:43 +0000236
shannon.woods@transgaming.com1d432bb2013-01-25 21:57:28 +0000237 arrayBoundsClamper.SetClampingStrategy(resources.ArrayIndexClampingStrategy);
238 clampingStrategy = resources.ArrayIndexClampingStrategy;
239
daniel@transgaming.comc23f4612012-11-28 19:42:57 +0000240 hashFunction = resources.HashFunction;
241
alokp@chromium.org07620a52010-09-23 17:53:56 +0000242 return true;
243}
244
Olli Etuaho6d40bbd2016-09-30 13:49:38 +0100245TIntermBlock *TCompiler::compileTreeForTesting(const char *const shaderStrings[],
246 size_t numStrings,
247 ShCompileOptions compileOptions)
alokp@chromium.org07620a52010-09-23 17:53:56 +0000248{
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200249 return compileTreeImpl(shaderStrings, numStrings, compileOptions);
250}
251
Olli Etuaho6d40bbd2016-09-30 13:49:38 +0100252TIntermBlock *TCompiler::compileTreeImpl(const char *const shaderStrings[],
253 size_t numStrings,
254 const ShCompileOptions compileOptions)
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200255{
alokp@chromium.org07620a52010-09-23 17:53:56 +0000256 clearResults();
257
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200258 ASSERT(numStrings > 0);
259 ASSERT(GetGlobalPoolAllocator());
alokp@chromium.org07620a52010-09-23 17:53:56 +0000260
David Yen0fbd1282015-02-02 14:46:09 -0800261 // Reset the extension behavior for each compilation unit.
262 ResetExtensionBehavior(extensionBehavior);
263
apatrick@chromium.org0f4cefe2011-01-26 19:30:57 +0000264 // First string is path of source file if flag is set. The actual source follows.
shannon.woods@transgaming.comd64b3da2013-02-28 23:19:26 +0000265 size_t firstSource = 0;
apatrick@chromium.org0f4cefe2011-01-26 19:30:57 +0000266 if (compileOptions & SH_SOURCE_PATH)
267 {
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200268 mSourcePath = shaderStrings[0];
apatrick@chromium.org0f4cefe2011-01-26 19:30:57 +0000269 ++firstSource;
270 }
271
Olli Etuahof119a262016-08-19 15:54:22 +0300272 TParseContext parseContext(symbolTable, extensionBehavior, shaderType, shaderSpec,
Olli Etuahoe1a94c62015-11-16 17:35:25 +0200273 compileOptions, true, infoSink, getResources());
Olli Etuaho853dc1a2014-11-06 17:25:48 +0200274
Olli Etuahoa6996682015-10-12 14:32:30 +0300275 parseContext.setFragmentPrecisionHighOnESSL1(fragmentPrecisionHigh);
Alok Priyadarshi8156b6b2013-09-23 14:56:58 -0400276 SetGlobalParseContext(&parseContext);
alokp@chromium.org07620a52010-09-23 17:53:56 +0000277
278 // We preserve symbols at the built-in level from compile-to-compile.
279 // Start pushing the user-defined symbols at global level.
Alok Priyadarshibc3f1ac2013-09-23 14:57:02 -0400280 TScopedSymbolTableLevel scopedSymbolLevel(&symbolTable);
alokp@chromium.org07620a52010-09-23 17:53:56 +0000281
282 // Parse shader.
283 bool success =
Jamie Madill6e06b1f2015-05-14 10:01:17 -0400284 (PaParseStrings(numStrings - firstSource, &shaderStrings[firstSource], nullptr, &parseContext) == 0) &&
285 (parseContext.getTreeRoot() != nullptr);
shannon.woods%transgaming.com@gtempaccount.com0bbed382013-04-13 03:38:07 +0000286
shannon.woods%transgaming.com@gtempaccount.com5524db02013-04-13 03:38:16 +0000287 shaderVersion = parseContext.getShaderVersion();
Zhenyao Modb9b40b2014-10-29 15:00:04 -0700288 if (success && MapSpecToShaderVersion(shaderSpec) < shaderVersion)
289 {
290 infoSink.info.prefix(EPrefixError);
291 infoSink.info << "unsupported shader version";
292 success = false;
293 }
shannon.woods%transgaming.com@gtempaccount.com0bbed382013-04-13 03:38:07 +0000294
Olli Etuaho6d40bbd2016-09-30 13:49:38 +0100295 TIntermBlock *root = nullptr;
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200296
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800297 if (success)
298 {
Zhenyao Mo94ac7b72014-10-15 18:22:08 -0700299 mPragma = parseContext.pragma();
Kenneth Russell8bad46d2016-07-01 19:52:52 -0700300 symbolTable.setGlobalInvariant(mPragma.stdgl.invariantAll);
Zhenyao Mo94ac7b72014-10-15 18:22:08 -0700301
Martin Radev802abe02016-08-04 17:48:32 +0300302 mComputeShaderLocalSizeDeclared = parseContext.isComputeShaderLocalSizeDeclared();
303 mComputeShaderLocalSize = parseContext.getComputeShaderLocalSize();
304
Jamie Madill6e06b1f2015-05-14 10:01:17 -0400305 root = parseContext.getTreeRoot();
alokp@chromium.orgb59a7782010-11-24 18:38:33 +0000306
Olli Etuahoa6996682015-10-12 14:32:30 +0300307 // Highp might have been auto-enabled based on shader version
308 fragmentPrecisionHigh = parseContext.getFragmentPrecisionHigh();
309
Jamie Madill6654bc92014-03-26 14:01:57 -0400310 // Disallow expressions deemed too complex.
311 if (success && (compileOptions & SH_LIMIT_EXPRESSION_COMPLEXITY))
312 success = limitExpressionComplexity(root);
313
Corentin Wallez71d147f2015-02-11 11:15:24 -0800314 // Create the function DAG and check there is no recursion
zmo@google.comb1762df2011-07-30 02:04:23 +0000315 if (success)
Corentin Wallez71d147f2015-02-11 11:15:24 -0800316 success = initCallDag(root);
317
318 if (success && (compileOptions & SH_LIMIT_CALL_STACK_DEPTH))
319 success = checkCallDepth();
320
321 // Checks which functions are used and if "main" exists
322 if (success)
323 {
324 functionMetadata.clear();
325 functionMetadata.resize(mCallDag.size());
326 success = tagUsedFunctions();
327 }
zmo@google.comb1762df2011-07-30 02:04:23 +0000328
Corentin Walleza094a8a2015-04-07 11:53:06 -0700329 if (success && !(compileOptions & SH_DONT_PRUNE_UNUSED_FUNCTIONS))
330 success = pruneUnusedFunctions(root);
331
Olli Etuahoc6833112015-04-22 15:15:54 +0300332 // Prune empty declarations to work around driver bugs and to keep declaration output simple.
333 if (success)
334 PruneEmptyDeclarations(root);
335
Jamie Madill183bde52014-07-02 15:31:19 -0400336 if (success && shaderVersion == 300 && shaderType == GL_FRAGMENT_SHADER)
Jamie Madill05a80ce2013-06-20 11:55:49 -0400337 success = validateOutputs(root);
338
Olli Etuaho5d91dda2015-06-18 15:47:46 +0300339 if (success && shouldRunLoopAndIndexingValidation(compileOptions))
alokp@chromium.orgb59a7782010-11-24 18:38:33 +0000340 success = validateLimitations(root);
alokp@chromium.org07620a52010-09-23 17:53:56 +0000341
Jamie Madilld5696192016-10-06 11:09:24 -0400342 // Fail compilation if precision emulation not supported.
343 if (success && getResources().WEBGL_debug_shader_precision &&
344 getPragma().debugShaderPrecision)
345 {
346 if (!EmulatePrecision::SupportedInLanguage(outputType))
347 {
348 infoSink.info.prefix(EPrefixError);
349 infoSink.info << "Precision emulation not supported for this output type.";
350 success = false;
351 }
352 }
353
zmo@google.com0c6bb7a2011-08-17 19:39:58 +0000354 // Unroll for-loop markup needs to happen after validateLimitations pass.
355 if (success && (compileOptions & SH_UNROLL_FOR_LOOP_WITH_INTEGER_INDEX))
Zhenyao Mo3cdfcce2014-03-07 13:00:08 -0800356 {
Olli Etuaho8a76dcc2015-12-10 20:25:12 +0200357 ForLoopUnrollMarker marker(ForLoopUnrollMarker::kIntegerIndex,
358 shouldRunLoopAndIndexingValidation(compileOptions));
Zhenyao Mo550c6002014-02-26 15:40:48 -0800359 root->traverse(&marker);
360 }
361 if (success && (compileOptions & SH_UNROLL_FOR_LOOP_WITH_SAMPLER_ARRAY_INDEX))
Zhenyao Mo3cdfcce2014-03-07 13:00:08 -0800362 {
Olli Etuaho8a76dcc2015-12-10 20:25:12 +0200363 ForLoopUnrollMarker marker(ForLoopUnrollMarker::kSamplerArrayIndex,
364 shouldRunLoopAndIndexingValidation(compileOptions));
Zhenyao Mo550c6002014-02-26 15:40:48 -0800365 root->traverse(&marker);
366 if (marker.samplerArrayIndexIsFloatLoopIndex())
367 {
368 infoSink.info.prefix(EPrefixError);
369 infoSink.info << "sampler array index is float loop index";
370 success = false;
371 }
372 }
zmo@google.com0c6bb7a2011-08-17 19:39:58 +0000373
zmo@google.com32e97312011-08-24 01:03:11 +0000374 // Built-in function emulation needs to happen after validateLimitations pass.
Olli Etuaho8efc5ad2015-03-03 17:21:10 +0200375 if (success)
376 {
Jamie Madill438dbcf2016-06-17 14:20:05 -0400377 // TODO(jmadill): Remove global pool allocator.
378 GetGlobalPoolAllocator()->lock();
Olli Etuaho8efc5ad2015-03-03 17:21:10 +0200379 initBuiltInFunctionEmulator(&builtInFunctionEmulator, compileOptions);
Jamie Madill438dbcf2016-06-17 14:20:05 -0400380 GetGlobalPoolAllocator()->unlock();
zmo@google.com32e97312011-08-24 01:03:11 +0000381 builtInFunctionEmulator.MarkBuiltInFunctionsForEmulation(root);
Olli Etuaho8efc5ad2015-03-03 17:21:10 +0200382 }
zmo@google.com32e97312011-08-24 01:03:11 +0000383
daniel@transgaming.com4167cc92013-01-11 04:11:53 +0000384 // Clamping uniform array bounds needs to happen after validateLimitations pass.
385 if (success && (compileOptions & SH_CLAMP_INDIRECT_ARRAY_BOUNDS))
386 arrayBoundsClamper.MarkIndirectArrayBoundsForClamping(root);
387
Ian Ewell924b7de2016-01-21 13:54:28 -0500388 // gl_Position is always written in compatibility output mode
389 if (success && shaderType == GL_VERTEX_SHADER &&
390 ((compileOptions & SH_INIT_GL_POSITION) ||
391 (outputType == SH_GLSL_COMPATIBILITY_OUTPUT)))
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800392 initializeGLPosition(root);
Zhenyao Moac44cd22013-09-23 14:57:09 -0400393
Qiankun Miao705a9192016-08-29 10:05:27 +0800394 if (success && !(compileOptions & SH_DONT_REMOVE_INVARIANT_FOR_FRAGMENT_INPUT) &&
395 shaderType == GL_FRAGMENT_SHADER && IsGLSL420OrNewer(outputType))
396 sh::RemoveInvariantDeclaration(root);
397
Corentin Wallezd4b50542015-09-28 12:19:26 -0700398 // This pass might emit short circuits so keep it before the short circuit unfolding
399 if (success && (compileOptions & SH_REWRITE_DO_WHILE_LOOPS))
400 RewriteDoWhile(root, getTemporaryIndex());
401
Qiankun Miao09cfac62016-09-06 17:25:16 +0800402 if (success && (compileOptions & SH_ADD_AND_TRUE_TO_LOOP_CONDITION))
403 sh::AddAndTrueToLoopCondition(root);
404
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800405 if (success && (compileOptions & SH_UNFOLD_SHORT_CIRCUIT))
406 {
Zhenyao Mo7cab38b2013-10-15 12:59:30 -0700407 UnfoldShortCircuitAST unfoldShortCircuit;
408 root->traverse(&unfoldShortCircuit);
409 unfoldShortCircuit.updateTree();
410 }
411
Olli Etuaho5c407bb2015-06-01 12:20:39 +0300412 if (success && (compileOptions & SH_REMOVE_POW_WITH_CONSTANT_EXPONENT))
413 {
414 RemovePow(root);
415 }
416
Olli Etuaho4dfe8092015-08-21 17:44:35 +0300417 if (success && shouldCollectVariables(compileOptions))
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800418 {
Zhenyao Mo74da9f22013-09-23 14:57:01 -0400419 collectVariables(root);
Qin Jiajia7835b522016-10-08 11:20:17 +0800420 if (compileOptions & SH_USE_UNUSED_STANDARD_SHARED_BLOCKS)
421 {
422 useAllMembersInUnusedStandardAndSharedBlocks(root);
423 }
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800424 if (compileOptions & SH_ENFORCE_PACKING_RESTRICTIONS)
425 {
gman@chromium.org8d804792012-10-17 21:33:48 +0000426 success = enforcePackingRestrictions();
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800427 if (!success)
428 {
Jamie Madill075edd82013-07-08 13:30:19 -0400429 infoSink.info.prefix(EPrefixError);
430 infoSink.info << "too many uniforms";
gman@chromium.org8d804792012-10-17 21:33:48 +0000431 }
432 }
Zhenyao Mo72111912016-07-20 17:45:56 -0700433 if (success && (compileOptions & SH_INIT_OUTPUT_VARIABLES))
434 {
Olli Etuaho27776e32016-07-22 14:00:56 +0300435 initializeOutputVariables(root);
Zhenyao Mo72111912016-07-20 17:45:56 -0700436 }
gman@chromium.org8d804792012-10-17 21:33:48 +0000437 }
zmo@google.comfd747b82011-04-23 01:30:07 +0000438
Zhenyao Mocd68fe72014-07-11 10:45:44 -0700439 if (success && (compileOptions & SH_SCALARIZE_VEC_AND_MAT_CONSTRUCTOR_ARGS))
440 {
Zhenyao Modaf56572014-08-06 16:18:30 -0700441 ScalarizeVecAndMatConstructorArgs scalarizer(
442 shaderType, fragmentPrecisionHigh);
Zhenyao Mocd68fe72014-07-11 10:45:44 -0700443 root->traverse(&scalarizer);
444 }
445
Zhenyao Moe740add2014-07-18 17:01:01 -0700446 if (success && (compileOptions & SH_REGENERATE_STRUCT_NAMES))
447 {
448 RegenerateStructNames gen(symbolTable, shaderVersion);
449 root->traverse(&gen);
450 }
Olli Etuaho3d932d82016-04-12 11:10:30 +0300451
Zhenyao Mo4e94fea2016-08-09 14:31:37 -0700452 if (success && shaderType == GL_FRAGMENT_SHADER && shaderVersion == 100 &&
453 compileResources.EXT_draw_buffers && compileResources.MaxDrawBuffers > 1 &&
454 IsExtensionEnabled(extensionBehavior, "GL_EXT_draw_buffers"))
455 {
456 EmulateGLFragColorBroadcast(root, compileResources.MaxDrawBuffers, &outputVariables);
457 }
458
Olli Etuaho3d932d82016-04-12 11:10:30 +0300459 if (success)
460 {
461 DeferGlobalInitializers(root);
462 }
alokp@chromium.org07620a52010-09-23 17:53:56 +0000463 }
464
Zhenyao Mo7faf1a12014-04-25 18:03:56 -0700465 SetGlobalParseContext(NULL);
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200466 if (success)
467 return root;
468
469 return NULL;
470}
471
Qiankun Miao7ebb97f2016-09-08 18:01:50 +0800472bool TCompiler::compile(const char *const shaderStrings[],
473 size_t numStrings,
474 ShCompileOptions compileOptionsIn)
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200475{
Corentin Wallez28b65282016-06-16 07:24:50 -0700476#if defined(ANGLE_ENABLE_FUZZER_CORPUS_OUTPUT)
477 DumpFuzzerCase(shaderStrings, numStrings, shaderType, shaderSpec, outputType, compileOptionsIn);
478#endif // defined(ANGLE_ENABLE_FUZZER_CORPUS_OUTPUT)
479
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200480 if (numStrings == 0)
481 return true;
482
Qiankun Miao7ebb97f2016-09-08 18:01:50 +0800483 ShCompileOptions compileOptions = compileOptionsIn;
Kenneth Russellbccc65d2016-07-19 16:48:43 -0700484
485 // Apply key workarounds.
486 if (shouldFlattenPragmaStdglInvariantAll())
487 {
488 // This should be harmless to do in all cases, but for the moment, do it only conditionally.
489 compileOptions |= SH_FLATTEN_PRAGMA_STDGL_INVARIANT_ALL;
490 }
491
Corentin Wallezb2792db2016-10-07 11:21:09 -0400492 ShCompileOptions unrollFlags =
493 SH_UNROLL_FOR_LOOP_WITH_INTEGER_INDEX | SH_UNROLL_FOR_LOOP_WITH_SAMPLER_ARRAY_INDEX;
494 if ((compileOptions & SH_ADD_AND_TRUE_TO_LOOP_CONDITION) != 0 &&
495 (compileOptions & unrollFlags) != 0)
496 {
497 infoSink.info.prefix(EPrefixError);
498 infoSink.info
499 << "Unsupported compile flag combination: unroll & ADD_TRUE_TO_LOOP_CONDITION";
500 return false;
501 }
502
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200503 TScopedPoolAllocator scopedAlloc(&allocator);
Olli Etuaho6d40bbd2016-09-30 13:49:38 +0100504 TIntermBlock *root = compileTreeImpl(shaderStrings, numStrings, compileOptions);
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200505
506 if (root)
507 {
508 if (compileOptions & SH_INTERMEDIATE_TREE)
509 TIntermediate::outputTree(root, infoSink.info);
510
511 if (compileOptions & SH_OBJECT_CODE)
512 translate(root, compileOptions);
513
514 // The IntermNode tree doesn't need to be deleted here, since the
515 // memory will be freed in a big chunk by the PoolAllocator.
516 return true;
517 }
518 return false;
alokp@chromium.org07620a52010-09-23 17:53:56 +0000519}
520
Nicolas Capens49a88872013-06-20 09:54:03 -0400521bool TCompiler::InitBuiltInSymbolTable(const ShBuiltInResources &resources)
alokp@chromium.org07620a52010-09-23 17:53:56 +0000522{
shannon.woods%transgaming.com@gtempaccount.com18b4c4b2013-04-13 03:31:40 +0000523 compileResources = resources;
Shannon Woods2d76e5f2014-05-16 17:46:41 -0400524 setResourceString();
shannonwoods@chromium.org2ac0be92013-05-30 00:02:27 +0000525
Nicolas Capens49a88872013-06-20 09:54:03 -0400526 assert(symbolTable.isEmpty());
527 symbolTable.push(); // COMMON_BUILTINS
528 symbolTable.push(); // ESSL1_BUILTINS
529 symbolTable.push(); // ESSL3_BUILTINS
Martin Radeve93d24e2016-07-28 12:06:05 +0300530 symbolTable.push(); // ESSL3_1_BUILTINS
shannonwoods@chromium.org2ac0be92013-05-30 00:02:27 +0000531
Nicolas Capens49a88872013-06-20 09:54:03 -0400532 TPublicType integer;
Martin Radev2cc85b32016-08-05 16:22:53 +0300533 integer.initializeBasicType(EbtInt);
Nicolas Capens49a88872013-06-20 09:54:03 -0400534
535 TPublicType floatingPoint;
Martin Radev2cc85b32016-08-05 16:22:53 +0300536 floatingPoint.initializeBasicType(EbtFloat);
Nicolas Capens49a88872013-06-20 09:54:03 -0400537
538 switch(shaderType)
539 {
Jamie Madill183bde52014-07-02 15:31:19 -0400540 case GL_FRAGMENT_SHADER:
Nicolas Capens49a88872013-06-20 09:54:03 -0400541 symbolTable.setDefaultPrecision(integer, EbpMedium);
542 break;
Jamie Madill183bde52014-07-02 15:31:19 -0400543 case GL_VERTEX_SHADER:
Nicolas Capens49a88872013-06-20 09:54:03 -0400544 symbolTable.setDefaultPrecision(integer, EbpHigh);
545 symbolTable.setDefaultPrecision(floatingPoint, EbpHigh);
546 break;
Martin Radev802abe02016-08-04 17:48:32 +0300547 case GL_COMPUTE_SHADER:
548 symbolTable.setDefaultPrecision(integer, EbpHigh);
549 symbolTable.setDefaultPrecision(floatingPoint, EbpHigh);
550 break;
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800551 default:
552 assert(false && "Language not supported");
Nicolas Capens49a88872013-06-20 09:54:03 -0400553 }
Olli Etuaho183d7e22015-11-20 15:59:09 +0200554 // Set defaults for sampler types that have default precision, even those that are
Zhenyao Moa5a1dfc2013-09-23 14:57:03 -0400555 // only available if an extension exists.
Olli Etuaho183d7e22015-11-20 15:59:09 +0200556 // New sampler types in ESSL3 don't have default precision. ESSL1 types do.
557 initSamplerDefaultPrecision(EbtSampler2D);
558 initSamplerDefaultPrecision(EbtSamplerCube);
559 // SamplerExternalOES is specified in the extension to have default precision.
560 initSamplerDefaultPrecision(EbtSamplerExternalOES);
561 // It isn't specified whether Sampler2DRect has default precision.
562 initSamplerDefaultPrecision(EbtSampler2DRect);
Nicolas Capens49a88872013-06-20 09:54:03 -0400563
Jamie Madill1b452142013-07-12 14:51:11 -0400564 InsertBuiltInFunctions(shaderType, shaderSpec, resources, symbolTable);
Nicolas Capens49a88872013-06-20 09:54:03 -0400565
566 IdentifyBuiltIns(shaderType, shaderSpec, resources, symbolTable);
567
568 return true;
alokp@chromium.org07620a52010-09-23 17:53:56 +0000569}
570
Olli Etuaho183d7e22015-11-20 15:59:09 +0200571void TCompiler::initSamplerDefaultPrecision(TBasicType samplerType)
572{
573 ASSERT(samplerType > EbtGuardSamplerBegin && samplerType < EbtGuardSamplerEnd);
574 TPublicType sampler;
Martin Radev2cc85b32016-08-05 16:22:53 +0300575 sampler.initializeBasicType(samplerType);
Olli Etuaho183d7e22015-11-20 15:59:09 +0200576 symbolTable.setDefaultPrecision(sampler, EbpLow);
577}
578
Shannon Woods2d76e5f2014-05-16 17:46:41 -0400579void TCompiler::setResourceString()
580{
581 std::ostringstream strstream;
Geoff Langb66a9092016-05-16 15:59:14 -0400582
583 // clang-format off
Shannon Woods2d76e5f2014-05-16 17:46:41 -0400584 strstream << ":MaxVertexAttribs:" << compileResources.MaxVertexAttribs
585 << ":MaxVertexUniformVectors:" << compileResources.MaxVertexUniformVectors
586 << ":MaxVaryingVectors:" << compileResources.MaxVaryingVectors
587 << ":MaxVertexTextureImageUnits:" << compileResources.MaxVertexTextureImageUnits
588 << ":MaxCombinedTextureImageUnits:" << compileResources.MaxCombinedTextureImageUnits
589 << ":MaxTextureImageUnits:" << compileResources.MaxTextureImageUnits
590 << ":MaxFragmentUniformVectors:" << compileResources.MaxFragmentUniformVectors
591 << ":MaxDrawBuffers:" << compileResources.MaxDrawBuffers
592 << ":OES_standard_derivatives:" << compileResources.OES_standard_derivatives
593 << ":OES_EGL_image_external:" << compileResources.OES_EGL_image_external
Geoff Langb66a9092016-05-16 15:59:14 -0400594 << ":OES_EGL_image_external_essl3:" << compileResources.OES_EGL_image_external_essl3
595 << ":NV_EGL_stream_consumer_external:" << compileResources.NV_EGL_stream_consumer_external
Shannon Woods2d76e5f2014-05-16 17:46:41 -0400596 << ":ARB_texture_rectangle:" << compileResources.ARB_texture_rectangle
597 << ":EXT_draw_buffers:" << compileResources.EXT_draw_buffers
598 << ":FragmentPrecisionHigh:" << compileResources.FragmentPrecisionHigh
599 << ":MaxExpressionComplexity:" << compileResources.MaxExpressionComplexity
600 << ":MaxCallStackDepth:" << compileResources.MaxCallStackDepth
Olli Etuaho19d1dc92016-03-08 17:18:46 +0200601 << ":MaxFunctionParameters:" << compileResources.MaxFunctionParameters
Kimmo Kinnunenb18609b2015-07-16 14:13:11 +0300602 << ":EXT_blend_func_extended:" << compileResources.EXT_blend_func_extended
Shannon Woods2d76e5f2014-05-16 17:46:41 -0400603 << ":EXT_frag_depth:" << compileResources.EXT_frag_depth
604 << ":EXT_shader_texture_lod:" << compileResources.EXT_shader_texture_lod
Erik Dahlströmea7a2122014-11-17 16:15:57 +0100605 << ":EXT_shader_framebuffer_fetch:" << compileResources.EXT_shader_framebuffer_fetch
606 << ":NV_shader_framebuffer_fetch:" << compileResources.NV_shader_framebuffer_fetch
607 << ":ARM_shader_framebuffer_fetch:" << compileResources.ARM_shader_framebuffer_fetch
Shannon Woods2d76e5f2014-05-16 17:46:41 -0400608 << ":MaxVertexOutputVectors:" << compileResources.MaxVertexOutputVectors
609 << ":MaxFragmentInputVectors:" << compileResources.MaxFragmentInputVectors
610 << ":MinProgramTexelOffset:" << compileResources.MinProgramTexelOffset
Olli Etuahoe61209a2014-09-26 12:01:17 +0300611 << ":MaxProgramTexelOffset:" << compileResources.MaxProgramTexelOffset
Kimmo Kinnunenb18609b2015-07-16 14:13:11 +0300612 << ":MaxDualSourceDrawBuffers:" << compileResources.MaxDualSourceDrawBuffers
Olli Etuaho853dc1a2014-11-06 17:25:48 +0200613 << ":NV_draw_buffers:" << compileResources.NV_draw_buffers
Martin Radeve93d24e2016-07-28 12:06:05 +0300614 << ":WEBGL_debug_shader_precision:" << compileResources.WEBGL_debug_shader_precision
615 << ":MaxImageUnits:" << compileResources.MaxImageUnits
616 << ":MaxVertexImageUniforms:" << compileResources.MaxVertexImageUniforms
617 << ":MaxFragmentImageUniforms:" << compileResources.MaxFragmentImageUniforms
618 << ":MaxComputeImageUniforms:" << compileResources.MaxComputeImageUniforms
619 << ":MaxCombinedImageUniforms:" << compileResources.MaxCombinedImageUniforms
620 << ":MaxCombinedShaderOutputResources:" << compileResources.MaxCombinedShaderOutputResources
621 << ":MaxComputeWorkGroupCountX:" << compileResources.MaxComputeWorkGroupCount[0]
622 << ":MaxComputeWorkGroupCountY:" << compileResources.MaxComputeWorkGroupCount[1]
623 << ":MaxComputeWorkGroupCountZ:" << compileResources.MaxComputeWorkGroupCount[2]
624 << ":MaxComputeWorkGroupSizeX:" << compileResources.MaxComputeWorkGroupSize[0]
625 << ":MaxComputeWorkGroupSizeY:" << compileResources.MaxComputeWorkGroupSize[1]
626 << ":MaxComputeWorkGroupSizeZ:" << compileResources.MaxComputeWorkGroupSize[2]
627 << ":MaxComputeUniformComponents:" << compileResources.MaxComputeUniformComponents
628 << ":MaxComputeTextureImageUnits:" << compileResources.MaxComputeTextureImageUnits
629 << ":MaxComputeAtomicCounters:" << compileResources.MaxComputeAtomicCounters
630 << ":MaxComputeAtomicCounterBuffers:" << compileResources.MaxComputeAtomicCounterBuffers
631 << ":MaxVertexAtomicCounters:" << compileResources.MaxVertexAtomicCounters
632 << ":MaxFragmentAtomicCounters:" << compileResources.MaxFragmentAtomicCounters
633 << ":MaxCombinedAtomicCounters:" << compileResources.MaxCombinedAtomicCounters
634 << ":MaxAtomicCounterBindings:" << compileResources.MaxAtomicCounterBindings
635 << ":MaxVertexAtomicCounterBuffers:" << compileResources.MaxVertexAtomicCounterBuffers
636 << ":MaxFragmentAtomicCounterBuffers:" << compileResources.MaxFragmentAtomicCounterBuffers
637 << ":MaxCombinedAtomicCounterBuffers:" << compileResources.MaxCombinedAtomicCounterBuffers
638 << ":MaxAtomicCounterBufferSize:" << compileResources.MaxAtomicCounterBufferSize;
Geoff Langb66a9092016-05-16 15:59:14 -0400639 // clang-format on
Shannon Woods2d76e5f2014-05-16 17:46:41 -0400640
641 builtInResourcesString = strstream.str();
642}
643
alokp@chromium.org07620a52010-09-23 17:53:56 +0000644void TCompiler::clearResults()
645{
daniel@transgaming.com4167cc92013-01-11 04:11:53 +0000646 arrayBoundsClamper.Cleanup();
alokp@chromium.org07620a52010-09-23 17:53:56 +0000647 infoSink.info.erase();
648 infoSink.obj.erase();
649 infoSink.debug.erase();
650
Jamie Madilled27c722014-07-02 15:31:23 -0400651 attributes.clear();
652 outputVariables.clear();
alokp@chromium.org07620a52010-09-23 17:53:56 +0000653 uniforms.clear();
Jamie Madill23a8a432014-07-09 13:27:42 -0400654 expandedUniforms.clear();
Zhenyao Mod2d340b2013-09-23 14:57:05 -0400655 varyings.clear();
Jamie Madilled27c722014-07-02 15:31:23 -0400656 interfaceBlocks.clear();
Kenneth Russellbccc65d2016-07-19 16:48:43 -0700657 variablesCollected = false;
zmo@google.coma3b4ab42011-09-16 00:53:26 +0000658
659 builtInFunctionEmulator.Cleanup();
daniel@transgaming.com0aa3b5a2012-11-28 19:43:24 +0000660
661 nameMap.clear();
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200662
663 mSourcePath = NULL;
Corentin Wallezd4b50542015-09-28 12:19:26 -0700664 mTemporaryIndex = 0;
alokp@chromium.org07620a52010-09-23 17:53:56 +0000665}
666
Corentin Wallez71d147f2015-02-11 11:15:24 -0800667bool TCompiler::initCallDag(TIntermNode *root)
zmo@google.comb1762df2011-07-30 02:04:23 +0000668{
Corentin Wallez71d147f2015-02-11 11:15:24 -0800669 mCallDag.clear();
670
671 switch (mCallDag.init(root, &infoSink.info))
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800672 {
Corentin Wallez71d147f2015-02-11 11:15:24 -0800673 case CallDAG::INITDAG_SUCCESS:
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800674 return true;
Corentin Wallez71d147f2015-02-11 11:15:24 -0800675 case CallDAG::INITDAG_RECURSION:
676 infoSink.info.prefix(EPrefixError);
677 infoSink.info << "Function recursion detected";
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800678 return false;
Corentin Wallez71d147f2015-02-11 11:15:24 -0800679 case CallDAG::INITDAG_UNDEFINED:
680 infoSink.info.prefix(EPrefixError);
681 infoSink.info << "Unimplemented function detected";
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800682 return false;
Corentin Wallez71d147f2015-02-11 11:15:24 -0800683 }
684
685 UNREACHABLE();
686 return true;
687}
688
689bool TCompiler::checkCallDepth()
690{
691 std::vector<int> depths(mCallDag.size());
692
693 for (size_t i = 0; i < mCallDag.size(); i++)
694 {
695 int depth = 0;
696 auto &record = mCallDag.getRecordFromIndex(i);
697
698 for (auto &calleeIndex : record.callees)
699 {
700 depth = std::max(depth, depths[calleeIndex] + 1);
701 }
702
703 depths[i] = depth;
704
705 if (depth >= maxCallStackDepth)
706 {
707 // Trace back the function chain to have a meaningful info log.
708 infoSink.info.prefix(EPrefixError);
709 infoSink.info << "Call stack too deep (larger than " << maxCallStackDepth
710 << ") with the following call chain: " << record.name;
711
Cooper Partin4d61f7e2015-08-12 10:56:50 -0700712 int currentFunction = static_cast<int>(i);
Corentin Wallez71d147f2015-02-11 11:15:24 -0800713 int currentDepth = depth;
714
715 while (currentFunction != -1)
716 {
717 infoSink.info << " -> " << mCallDag.getRecordFromIndex(currentFunction).name;
718
719 int nextFunction = -1;
720 for (auto& calleeIndex : mCallDag.getRecordFromIndex(currentFunction).callees)
721 {
722 if (depths[calleeIndex] == currentDepth - 1)
723 {
724 currentDepth--;
725 nextFunction = calleeIndex;
726 }
727 }
728
729 currentFunction = nextFunction;
730 }
731
732 return false;
733 }
734 }
735
736 return true;
737}
738
739bool TCompiler::tagUsedFunctions()
740{
741 // Search from main, starting from the end of the DAG as it usually is the root.
Cooper Partin4d61f7e2015-08-12 10:56:50 -0700742 for (size_t i = mCallDag.size(); i-- > 0;)
Corentin Wallez71d147f2015-02-11 11:15:24 -0800743 {
744 if (mCallDag.getRecordFromIndex(i).name == "main(")
745 {
746 internalTagUsedFunction(i);
747 return true;
748 }
749 }
750
751 infoSink.info.prefix(EPrefixError);
Olli Etuaho792a41d2015-12-15 12:39:16 +0200752 infoSink.info << "Missing main()\n";
Corentin Wallez71d147f2015-02-11 11:15:24 -0800753 return false;
754}
755
756void TCompiler::internalTagUsedFunction(size_t index)
757{
758 if (functionMetadata[index].used)
759 {
760 return;
761 }
762
763 functionMetadata[index].used = true;
764
765 for (int calleeIndex : mCallDag.getRecordFromIndex(index).callees)
766 {
767 internalTagUsedFunction(calleeIndex);
zmo@google.comb1762df2011-07-30 02:04:23 +0000768 }
769}
770
Corentin Walleza094a8a2015-04-07 11:53:06 -0700771// A predicate for the stl that returns if a top-level node is unused
772class TCompiler::UnusedPredicate
773{
774 public:
775 UnusedPredicate(const CallDAG *callDag, const std::vector<FunctionMetadata> *metadatas)
776 : mCallDag(callDag),
777 mMetadatas(metadatas)
778 {
779 }
780
781 bool operator ()(TIntermNode *node)
782 {
783 const TIntermAggregate *asAggregate = node->getAsAggregate();
Olli Etuaho336b1472016-10-05 16:37:55 +0100784 const TIntermFunctionDefinition *asFunction = node->getAsFunctionDefinition();
Corentin Walleza094a8a2015-04-07 11:53:06 -0700785
Olli Etuaho336b1472016-10-05 16:37:55 +0100786 const TFunctionSymbolInfo *functionInfo = nullptr;
787
788 if (asFunction)
789 {
790 functionInfo = asFunction->getFunctionSymbolInfo();
791 }
792 else if (asAggregate)
793 {
794 if (asAggregate->getOp() == EOpPrototype)
795 {
796 functionInfo = asAggregate->getFunctionSymbolInfo();
797 }
798 }
799 if (functionInfo == nullptr)
Corentin Walleza094a8a2015-04-07 11:53:06 -0700800 {
801 return false;
802 }
803
Olli Etuaho336b1472016-10-05 16:37:55 +0100804 size_t callDagIndex = mCallDag->findIndex(functionInfo);
Corentin Walleza094a8a2015-04-07 11:53:06 -0700805 if (callDagIndex == CallDAG::InvalidIndex)
806 {
807 // This happens only for unimplemented prototypes which are thus unused
Olli Etuaho336b1472016-10-05 16:37:55 +0100808 ASSERT(asAggregate && asAggregate->getOp() == EOpPrototype);
Corentin Walleza094a8a2015-04-07 11:53:06 -0700809 return true;
810 }
811
812 ASSERT(callDagIndex < mMetadatas->size());
813 return !(*mMetadatas)[callDagIndex].used;
814 }
815
816 private:
817 const CallDAG *mCallDag;
818 const std::vector<FunctionMetadata> *mMetadatas;
819};
820
Olli Etuaho6d40bbd2016-09-30 13:49:38 +0100821bool TCompiler::pruneUnusedFunctions(TIntermBlock *root)
Corentin Walleza094a8a2015-04-07 11:53:06 -0700822{
Corentin Walleza094a8a2015-04-07 11:53:06 -0700823 UnusedPredicate isUnused(&mCallDag, &functionMetadata);
Olli Etuaho6d40bbd2016-09-30 13:49:38 +0100824 TIntermSequence *sequence = root->getSequence();
Corentin Wallezb081e782015-07-20 05:40:04 -0700825
826 if (!sequence->empty())
827 {
828 sequence->erase(std::remove_if(sequence->begin(), sequence->end(), isUnused), sequence->end());
829 }
Corentin Walleza094a8a2015-04-07 11:53:06 -0700830
831 return true;
832}
833
Jamie Madill05a80ce2013-06-20 11:55:49 -0400834bool TCompiler::validateOutputs(TIntermNode* root)
835{
Kimmo Kinnunenb18609b2015-07-16 14:13:11 +0300836 ValidateOutputs validateOutputs(getExtensionBehavior(), compileResources.MaxDrawBuffers);
Jamie Madill05a80ce2013-06-20 11:55:49 -0400837 root->traverse(&validateOutputs);
Kimmo Kinnunenb18609b2015-07-16 14:13:11 +0300838 return (validateOutputs.validateAndCountErrors(infoSink.info) == 0);
Jamie Madill05a80ce2013-06-20 11:55:49 -0400839}
840
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800841bool TCompiler::validateLimitations(TIntermNode* root)
842{
Olli Etuaho8a76dcc2015-12-10 20:25:12 +0200843 ValidateLimitations validate(shaderType, &infoSink.info);
alokp@chromium.orgb59a7782010-11-24 18:38:33 +0000844 root->traverse(&validate);
845 return validate.numErrors() == 0;
846}
847
Jamie Madilleb1a0102013-07-08 13:31:38 -0400848bool TCompiler::limitExpressionComplexity(TIntermNode* root)
849{
Jamie Madill6654bc92014-03-26 14:01:57 -0400850 TMaxDepthTraverser traverser(maxExpressionComplexity+1);
Jamie Madilleb1a0102013-07-08 13:31:38 -0400851 root->traverse(&traverser);
Jamie Madill6654bc92014-03-26 14:01:57 -0400852
853 if (traverser.getMaxDepth() > maxExpressionComplexity)
854 {
855 infoSink.info << "Expression too complex.";
856 return false;
857 }
858
Olli Etuaho19d1dc92016-03-08 17:18:46 +0200859 if (!ValidateMaxParameters::validate(root, maxFunctionParameters))
860 {
861 infoSink.info << "Function has too many parameters.";
862 return false;
863 }
864
Jamie Madilleb1a0102013-07-08 13:31:38 -0400865 return true;
866}
867
Zhenyao Mo74da9f22013-09-23 14:57:01 -0400868void TCompiler::collectVariables(TIntermNode* root)
alokp@chromium.org07620a52010-09-23 17:53:56 +0000869{
Kenneth Russellbccc65d2016-07-19 16:48:43 -0700870 if (!variablesCollected)
871 {
872 sh::CollectVariables collect(&attributes, &outputVariables, &uniforms, &varyings,
873 &interfaceBlocks, hashFunction, symbolTable, extensionBehavior);
874 root->traverse(&collect);
Jamie Madill23a8a432014-07-09 13:27:42 -0400875
Kenneth Russellbccc65d2016-07-19 16:48:43 -0700876 // This is for enforcePackingRestriction().
877 sh::ExpandUniforms(uniforms, &expandedUniforms);
878 variablesCollected = true;
879 }
alokp@chromium.org07620a52010-09-23 17:53:56 +0000880}
zmo@google.comfd747b82011-04-23 01:30:07 +0000881
Corentin Wallez1df16022016-10-27 08:16:56 -0400882bool TCompiler::shouldCollectVariables(ShCompileOptions compileOptions)
883{
884 return (compileOptions & SH_VARIABLES) != 0;
885}
886
887bool TCompiler::wereVariablesCollected() const
888{
889 return variablesCollected;
890}
891
gman@chromium.org8d804792012-10-17 21:33:48 +0000892bool TCompiler::enforcePackingRestrictions()
893{
894 VariablePacker packer;
Jamie Madill23a8a432014-07-09 13:27:42 -0400895 return packer.CheckVariablesWithinPackingLimits(maxUniformVectors, expandedUniforms);
gman@chromium.org8d804792012-10-17 21:33:48 +0000896}
897
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800898void TCompiler::initializeGLPosition(TIntermNode* root)
899{
Zhenyao Mo72111912016-07-20 17:45:56 -0700900 InitVariableList list;
901 sh::ShaderVariable var(GL_FLOAT_VEC4, 0);
902 var.name = "gl_Position";
903 list.push_back(var);
904 InitializeVariables(root, list);
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800905}
906
Qin Jiajia7835b522016-10-08 11:20:17 +0800907void TCompiler::useAllMembersInUnusedStandardAndSharedBlocks(TIntermNode *root)
908{
909 sh::InterfaceBlockList list;
910
911 for (auto block : interfaceBlocks)
912 {
913 if (!block.staticUse &&
914 (block.layout == sh::BLOCKLAYOUT_STANDARD || block.layout == sh::BLOCKLAYOUT_SHARED))
915 {
916 list.push_back(block);
917 }
918 }
919
920 sh::UseInterfaceBlockFields(root, list);
921}
922
Olli Etuaho27776e32016-07-22 14:00:56 +0300923void TCompiler::initializeOutputVariables(TIntermNode *root)
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800924{
Zhenyao Mo72111912016-07-20 17:45:56 -0700925 InitVariableList list;
926 if (shaderType == GL_VERTEX_SHADER)
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800927 {
Zhenyao Mo72111912016-07-20 17:45:56 -0700928 for (auto var : varyings)
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800929 {
Zhenyao Mof9312682016-07-22 12:51:31 -0700930 list.push_back(var);
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800931 }
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800932 }
Zhenyao Mo72111912016-07-20 17:45:56 -0700933 else
934 {
935 ASSERT(shaderType == GL_FRAGMENT_SHADER);
936 for (auto var : outputVariables)
937 {
938 list.push_back(var);
939 }
940 }
941 InitializeVariables(root, list);
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800942}
943
zmo@google.com5601ea02011-06-10 18:23:25 +0000944const TExtensionBehavior& TCompiler::getExtensionBehavior() const
945{
946 return extensionBehavior;
947}
zmo@google.com32e97312011-08-24 01:03:11 +0000948
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200949const char *TCompiler::getSourcePath() const
950{
951 return mSourcePath;
952}
953
shannon.woods%transgaming.com@gtempaccount.com18b4c4b2013-04-13 03:31:40 +0000954const ShBuiltInResources& TCompiler::getResources() const
955{
956 return compileResources;
957}
958
daniel@transgaming.com4167cc92013-01-11 04:11:53 +0000959const ArrayBoundsClamper& TCompiler::getArrayBoundsClamper() const
960{
961 return arrayBoundsClamper;
962}
963
shannon.woods@transgaming.com1d432bb2013-01-25 21:57:28 +0000964ShArrayIndexClampingStrategy TCompiler::getArrayIndexClampingStrategy() const
965{
966 return clampingStrategy;
967}
968
Olli Etuaho8efc5ad2015-03-03 17:21:10 +0200969const BuiltInFunctionEmulator& TCompiler::getBuiltInFunctionEmulator() const
shannon.woods@transgaming.com1d432bb2013-01-25 21:57:28 +0000970{
971 return builtInFunctionEmulator;
972}
Zhenyao Mo94ac7b72014-10-15 18:22:08 -0700973
Qiankun Miao7ebb97f2016-09-08 18:01:50 +0800974void TCompiler::writePragma(ShCompileOptions compileOptions)
Zhenyao Mo94ac7b72014-10-15 18:22:08 -0700975{
Kenneth Russellbccc65d2016-07-19 16:48:43 -0700976 if (!(compileOptions & SH_FLATTEN_PRAGMA_STDGL_INVARIANT_ALL))
977 {
978 TInfoSinkBase &sink = infoSink.obj;
979 if (mPragma.stdgl.invariantAll)
980 sink << "#pragma STDGL invariant(all)\n";
981 }
982}
983
984bool TCompiler::isVaryingDefined(const char *varyingName)
985{
986 ASSERT(variablesCollected);
987 for (size_t ii = 0; ii < varyings.size(); ++ii)
988 {
989 if (varyings[ii].name == varyingName)
990 {
991 return true;
992 }
993 }
994
995 return false;
Zhenyao Mo94ac7b72014-10-15 18:22:08 -0700996}