blob: 74c0104757e2e6b7f2a429a68dff26e777a7d130 [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"
Geoff Lang17732822013-08-29 13:46:49 -040018#include "compiler/translator/ForLoopUnroll.h"
19#include "compiler/translator/Initialize.h"
Geoff Lang17732822013-08-29 13:46:49 -040020#include "compiler/translator/InitializeParseContext.h"
Zhenyao Mo4a667fe2014-02-11 12:35:01 -080021#include "compiler/translator/InitializeVariables.h"
Jamie Madill6b9cb252013-10-17 10:45:47 -040022#include "compiler/translator/ParseContext.h"
Olli Etuahoc6833112015-04-22 15:15:54 +030023#include "compiler/translator/PruneEmptyDeclarations.h"
Zhenyao Moe740add2014-07-18 17:01:01 -070024#include "compiler/translator/RegenerateStructNames.h"
Olli Etuaho5c407bb2015-06-01 12:20:39 +030025#include "compiler/translator/RemovePow.h"
Corentin Wallezd4b50542015-09-28 12:19:26 -070026#include "compiler/translator/RewriteDoWhile.h"
Zhenyao Mocd68fe72014-07-11 10:45:44 -070027#include "compiler/translator/ScalarizeVecAndMatConstructorArgs.h"
Zhenyao Mo7cab38b2013-10-15 12:59:30 -070028#include "compiler/translator/UnfoldShortCircuitAST.h"
Geoff Lang17732822013-08-29 13:46:49 -040029#include "compiler/translator/ValidateLimitations.h"
Olli Etuaho19d1dc92016-03-08 17:18:46 +020030#include "compiler/translator/ValidateMaxParameters.h"
Geoff Lang17732822013-08-29 13:46:49 -040031#include "compiler/translator/ValidateOutputs.h"
32#include "compiler/translator/VariablePacker.h"
shannon.woods@transgaming.comda1ed362013-01-25 21:54:57 +000033#include "third_party/compiler/ArrayBoundsClamper.h"
Corentin Wallez28b65282016-06-16 07:24:50 -070034
35namespace
36{
37
38#if defined(ANGLE_ENABLE_FUZZER_CORPUS_OUTPUT)
39void DumpFuzzerCase(char const *const *shaderStrings,
40 size_t numStrings,
41 uint32_t type,
42 uint32_t spec,
43 uint32_t output,
44 uint64_t options)
45{
46 static int fileIndex = 0;
47
48 std::ostringstream o;
49 o << "corpus/" << fileIndex++ << ".sample";
50 std::string s = o.str();
51
52 // Must match the input format of the fuzzer
53 FILE *f = fopen(s.c_str(), "w");
54 fwrite(&type, sizeof(type), 1, f);
55 fwrite(&spec, sizeof(spec), 1, f);
56 fwrite(&output, sizeof(output), 1, f);
57 fwrite(&options, sizeof(options), 1, f);
58
59 char zero[128 - 20] = {0};
60 fwrite(&zero, 128 - 20, 1, f);
61
62 for (size_t i = 0; i < numStrings; i++)
63 {
64 fwrite(shaderStrings[i], sizeof(char), strlen(shaderStrings[i]), f);
65 }
66 fwrite(&zero, 1, 1, f);
67
68 fclose(f);
69}
70#endif // defined(ANGLE_ENABLE_FUZZER_CORPUS_OUTPUT)
71} // anonymous namespace
72
Jamie Madill5508f392014-02-20 13:31:36 -050073bool IsWebGLBasedSpec(ShShaderSpec spec)
maxvujovic@gmail.com430f5e02012-06-08 17:47:59 +000074{
Qiankun Miaoc2c5fc42016-08-31 15:24:22 +080075 return (spec == SH_WEBGL_SPEC || spec == SH_WEBGL2_SPEC || spec == SH_WEBGL3_SPEC);
maxvujovic@gmail.com430f5e02012-06-08 17:47:59 +000076}
77
Qingqing Dengad0d0792015-04-08 14:25:06 -070078bool IsGLSL130OrNewer(ShShaderOutput output)
79{
80 return (output == SH_GLSL_130_OUTPUT ||
Geoff Lang8273e002015-06-15 13:40:19 -070081 output == SH_GLSL_140_OUTPUT ||
82 output == SH_GLSL_150_CORE_OUTPUT ||
83 output == SH_GLSL_330_CORE_OUTPUT ||
84 output == SH_GLSL_400_CORE_OUTPUT ||
Qingqing Dengad0d0792015-04-08 14:25:06 -070085 output == SH_GLSL_410_CORE_OUTPUT ||
Geoff Lang8273e002015-06-15 13:40:19 -070086 output == SH_GLSL_420_CORE_OUTPUT ||
87 output == SH_GLSL_430_CORE_OUTPUT ||
88 output == SH_GLSL_440_CORE_OUTPUT ||
89 output == SH_GLSL_450_CORE_OUTPUT);
Qingqing Dengad0d0792015-04-08 14:25:06 -070090}
91
Zhenyao Mo7faf1a12014-04-25 18:03:56 -070092size_t GetGlobalMaxTokenSize(ShShaderSpec spec)
Jamie Madill88f6e942014-02-19 10:27:53 -050093{
Jamie Madill88f6e942014-02-19 10:27:53 -050094 // WebGL defines a max token legnth of 256, while ES2 leaves max token
95 // size undefined. ES3 defines a max size of 1024 characters.
Zhenyao Modb9b40b2014-10-29 15:00:04 -070096 switch (spec)
Jamie Madill88f6e942014-02-19 10:27:53 -050097 {
Zhenyao Modb9b40b2014-10-29 15:00:04 -070098 case SH_WEBGL_SPEC:
Jamie Madill88f6e942014-02-19 10:27:53 -050099 return 256;
Zhenyao Modb9b40b2014-10-29 15:00:04 -0700100 default:
Jamie Madill88f6e942014-02-19 10:27:53 -0500101 return 1024;
102 }
103}
104
alokp@chromium.orgbafcbaa2010-11-23 19:07:43 +0000105namespace {
Zhenyao Modb9b40b2014-10-29 15:00:04 -0700106
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800107class TScopedPoolAllocator
108{
109 public:
110 TScopedPoolAllocator(TPoolAllocator* allocator) : mAllocator(allocator)
111 {
Alok Priyadarshibc3f1ac2013-09-23 14:57:02 -0400112 mAllocator->push();
alokp@chromium.orgbafcbaa2010-11-23 19:07:43 +0000113 SetGlobalPoolAllocator(mAllocator);
114 }
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800115 ~TScopedPoolAllocator()
116 {
alokp@chromium.orgbafcbaa2010-11-23 19:07:43 +0000117 SetGlobalPoolAllocator(NULL);
Alok Priyadarshibc3f1ac2013-09-23 14:57:02 -0400118 mAllocator->pop();
alokp@chromium.orgbafcbaa2010-11-23 19:07:43 +0000119 }
120
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800121 private:
alokp@chromium.orgbafcbaa2010-11-23 19:07:43 +0000122 TPoolAllocator* mAllocator;
Alok Priyadarshibc3f1ac2013-09-23 14:57:02 -0400123};
124
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800125class TScopedSymbolTableLevel
126{
127 public:
128 TScopedSymbolTableLevel(TSymbolTable* table) : mTable(table)
129 {
Alok Priyadarshibc3f1ac2013-09-23 14:57:02 -0400130 ASSERT(mTable->atBuiltInLevel());
131 mTable->push();
132 }
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800133 ~TScopedSymbolTableLevel()
134 {
Alok Priyadarshibc3f1ac2013-09-23 14:57:02 -0400135 while (!mTable->atBuiltInLevel())
136 mTable->pop();
137 }
138
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800139 private:
Alok Priyadarshibc3f1ac2013-09-23 14:57:02 -0400140 TSymbolTable* mTable;
alokp@chromium.orgbafcbaa2010-11-23 19:07:43 +0000141};
Zhenyao Modb9b40b2014-10-29 15:00:04 -0700142
143int MapSpecToShaderVersion(ShShaderSpec spec)
144{
145 switch (spec)
146 {
147 case SH_GLES2_SPEC:
148 case SH_WEBGL_SPEC:
Zhenyao Modb9b40b2014-10-29 15:00:04 -0700149 return 100;
150 case SH_GLES3_SPEC:
151 case SH_WEBGL2_SPEC:
152 return 300;
Martin Radev1be913c2016-07-11 17:59:16 +0300153 case SH_GLES3_1_SPEC:
154 case SH_WEBGL3_SPEC:
155 return 310;
Zhenyao Modb9b40b2014-10-29 15:00:04 -0700156 default:
157 UNREACHABLE();
158 return 0;
159 }
160}
161
alokp@chromium.orgbafcbaa2010-11-23 19:07:43 +0000162} // namespace
163
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800164TShHandleBase::TShHandleBase()
165{
alokp@chromium.orgbafcbaa2010-11-23 19:07:43 +0000166 allocator.push();
167 SetGlobalPoolAllocator(&allocator);
168}
169
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800170TShHandleBase::~TShHandleBase()
171{
alokp@chromium.orgbafcbaa2010-11-23 19:07:43 +0000172 SetGlobalPoolAllocator(NULL);
173 allocator.popAll();
174}
175
Jamie Madill183bde52014-07-02 15:31:19 -0400176TCompiler::TCompiler(sh::GLenum type, ShShaderSpec spec, ShShaderOutput output)
Kenneth Russellbccc65d2016-07-19 16:48:43 -0700177 : variablesCollected(false),
178 shaderType(type),
zmo@google.comf420c422011-09-12 18:27:59 +0000179 shaderSpec(spec),
Jamie Madill68fe74a2014-05-27 12:56:01 -0400180 outputType(output),
Jamie Madilleb1a0102013-07-08 13:31:38 -0400181 maxUniformVectors(0),
182 maxExpressionComplexity(0),
183 maxCallStackDepth(0),
Olli Etuaho19d1dc92016-03-08 17:18:46 +0200184 maxFunctionParameters(0),
shannon.woods%transgaming.com@gtempaccount.comcbb6b6a2013-04-13 03:27:47 +0000185 fragmentPrecisionHigh(false),
shannon.woods@transgaming.com1d432bb2013-01-25 21:57:28 +0000186 clampingStrategy(SH_CLAMP_WITH_CLAMP_INTRINSIC),
Olli Etuaho8efc5ad2015-03-03 17:21:10 +0200187 builtInFunctionEmulator(),
Corentin Wallezd4b50542015-09-28 12:19:26 -0700188 mSourcePath(NULL),
Martin Radev802abe02016-08-04 17:48:32 +0300189 mComputeShaderLocalSizeDeclared(false),
Corentin Wallezd4b50542015-09-28 12:19:26 -0700190 mTemporaryIndex(0)
alokp@chromium.org4888ceb2010-10-01 21:13:12 +0000191{
Martin Radev802abe02016-08-04 17:48:32 +0300192 mComputeShaderLocalSize.fill(1);
alokp@chromium.org4888ceb2010-10-01 21:13:12 +0000193}
194
195TCompiler::~TCompiler()
196{
197}
198
Qiankun Miao7ebb97f2016-09-08 18:01:50 +0800199bool TCompiler::shouldRunLoopAndIndexingValidation(ShCompileOptions compileOptions) const
Olli Etuaho5d91dda2015-06-18 15:47:46 +0300200{
201 // If compiling an ESSL 1.00 shader for WebGL, or if its been requested through the API,
202 // validate loop and indexing as well (to verify that the shader only uses minimal functionality
203 // of ESSL 1.00 as in Appendix A of the spec).
204 return (IsWebGLBasedSpec(shaderSpec) && shaderVersion == 100) ||
205 (compileOptions & SH_VALIDATE_LOOP_INDEXING);
206}
207
alokp@chromium.org4888ceb2010-10-01 21:13:12 +0000208bool TCompiler::Init(const ShBuiltInResources& resources)
alokp@chromium.org07620a52010-09-23 17:53:56 +0000209{
shannon.woods%transgaming.com@gtempaccount.com0bbed382013-04-13 03:38:07 +0000210 shaderVersion = 100;
Jamie Madill183bde52014-07-02 15:31:19 -0400211 maxUniformVectors = (shaderType == GL_VERTEX_SHADER) ?
gman@chromium.org8d804792012-10-17 21:33:48 +0000212 resources.MaxVertexUniformVectors :
213 resources.MaxFragmentUniformVectors;
Jamie Madilleb1a0102013-07-08 13:31:38 -0400214 maxExpressionComplexity = resources.MaxExpressionComplexity;
Olli Etuaho19d1dc92016-03-08 17:18:46 +0200215 maxCallStackDepth = resources.MaxCallStackDepth;
216 maxFunctionParameters = resources.MaxFunctionParameters;
Alok Priyadarshibc3f1ac2013-09-23 14:57:02 -0400217
218 SetGlobalPoolAllocator(&allocator);
alokp@chromium.orgbafcbaa2010-11-23 19:07:43 +0000219
alokp@chromium.org07620a52010-09-23 17:53:56 +0000220 // Generate built-in symbol table.
221 if (!InitBuiltInSymbolTable(resources))
222 return false;
alokp@chromium.org07620a52010-09-23 17:53:56 +0000223 InitExtensionBehavior(resources, extensionBehavior);
shannon.woods%transgaming.com@gtempaccount.comcbb6b6a2013-04-13 03:27:47 +0000224 fragmentPrecisionHigh = resources.FragmentPrecisionHigh == 1;
alokp@chromium.orgbafcbaa2010-11-23 19:07:43 +0000225
shannon.woods@transgaming.com1d432bb2013-01-25 21:57:28 +0000226 arrayBoundsClamper.SetClampingStrategy(resources.ArrayIndexClampingStrategy);
227 clampingStrategy = resources.ArrayIndexClampingStrategy;
228
daniel@transgaming.comc23f4612012-11-28 19:42:57 +0000229 hashFunction = resources.HashFunction;
230
alokp@chromium.org07620a52010-09-23 17:53:56 +0000231 return true;
232}
233
Qiankun Miao7ebb97f2016-09-08 18:01:50 +0800234TIntermNode *TCompiler::compileTreeForTesting(const char *const shaderStrings[],
235 size_t numStrings,
236 ShCompileOptions compileOptions)
alokp@chromium.org07620a52010-09-23 17:53:56 +0000237{
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200238 return compileTreeImpl(shaderStrings, numStrings, compileOptions);
239}
240
Olli Etuahoa7b6db72015-08-19 14:26:30 +0300241TIntermNode *TCompiler::compileTreeImpl(const char *const shaderStrings[],
242 size_t numStrings,
Qiankun Miao7ebb97f2016-09-08 18:01:50 +0800243 const ShCompileOptions compileOptions)
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200244{
alokp@chromium.org07620a52010-09-23 17:53:56 +0000245 clearResults();
246
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200247 ASSERT(numStrings > 0);
248 ASSERT(GetGlobalPoolAllocator());
alokp@chromium.org07620a52010-09-23 17:53:56 +0000249
David Yen0fbd1282015-02-02 14:46:09 -0800250 // Reset the extension behavior for each compilation unit.
251 ResetExtensionBehavior(extensionBehavior);
252
apatrick@chromium.org0f4cefe2011-01-26 19:30:57 +0000253 // First string is path of source file if flag is set. The actual source follows.
shannon.woods@transgaming.comd64b3da2013-02-28 23:19:26 +0000254 size_t firstSource = 0;
apatrick@chromium.org0f4cefe2011-01-26 19:30:57 +0000255 if (compileOptions & SH_SOURCE_PATH)
256 {
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200257 mSourcePath = shaderStrings[0];
apatrick@chromium.org0f4cefe2011-01-26 19:30:57 +0000258 ++firstSource;
259 }
260
Olli Etuahof119a262016-08-19 15:54:22 +0300261 TParseContext parseContext(symbolTable, extensionBehavior, shaderType, shaderSpec,
Olli Etuahoe1a94c62015-11-16 17:35:25 +0200262 compileOptions, true, infoSink, getResources());
Olli Etuaho853dc1a2014-11-06 17:25:48 +0200263
Olli Etuahoa6996682015-10-12 14:32:30 +0300264 parseContext.setFragmentPrecisionHighOnESSL1(fragmentPrecisionHigh);
Alok Priyadarshi8156b6b2013-09-23 14:56:58 -0400265 SetGlobalParseContext(&parseContext);
alokp@chromium.org07620a52010-09-23 17:53:56 +0000266
267 // We preserve symbols at the built-in level from compile-to-compile.
268 // Start pushing the user-defined symbols at global level.
Alok Priyadarshibc3f1ac2013-09-23 14:57:02 -0400269 TScopedSymbolTableLevel scopedSymbolLevel(&symbolTable);
alokp@chromium.org07620a52010-09-23 17:53:56 +0000270
271 // Parse shader.
272 bool success =
Jamie Madill6e06b1f2015-05-14 10:01:17 -0400273 (PaParseStrings(numStrings - firstSource, &shaderStrings[firstSource], nullptr, &parseContext) == 0) &&
274 (parseContext.getTreeRoot() != nullptr);
shannon.woods%transgaming.com@gtempaccount.com0bbed382013-04-13 03:38:07 +0000275
shannon.woods%transgaming.com@gtempaccount.com5524db02013-04-13 03:38:16 +0000276 shaderVersion = parseContext.getShaderVersion();
Zhenyao Modb9b40b2014-10-29 15:00:04 -0700277 if (success && MapSpecToShaderVersion(shaderSpec) < shaderVersion)
278 {
279 infoSink.info.prefix(EPrefixError);
280 infoSink.info << "unsupported shader version";
281 success = false;
282 }
shannon.woods%transgaming.com@gtempaccount.com0bbed382013-04-13 03:38:07 +0000283
Jamie Madill6e06b1f2015-05-14 10:01:17 -0400284 TIntermNode *root = nullptr;
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200285
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800286 if (success)
287 {
Zhenyao Mo94ac7b72014-10-15 18:22:08 -0700288 mPragma = parseContext.pragma();
Kenneth Russell8bad46d2016-07-01 19:52:52 -0700289 symbolTable.setGlobalInvariant(mPragma.stdgl.invariantAll);
Zhenyao Mo94ac7b72014-10-15 18:22:08 -0700290
Martin Radev802abe02016-08-04 17:48:32 +0300291 mComputeShaderLocalSizeDeclared = parseContext.isComputeShaderLocalSizeDeclared();
292 mComputeShaderLocalSize = parseContext.getComputeShaderLocalSize();
293
Jamie Madill6e06b1f2015-05-14 10:01:17 -0400294 root = parseContext.getTreeRoot();
Olli Etuahof119a262016-08-19 15:54:22 +0300295 root = TIntermediate::PostProcess(root);
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
zmo@google.com0c6bb7a2011-08-17 19:39:58 +0000332 // Unroll for-loop markup needs to happen after validateLimitations pass.
333 if (success && (compileOptions & SH_UNROLL_FOR_LOOP_WITH_INTEGER_INDEX))
Zhenyao Mo3cdfcce2014-03-07 13:00:08 -0800334 {
Olli Etuaho8a76dcc2015-12-10 20:25:12 +0200335 ForLoopUnrollMarker marker(ForLoopUnrollMarker::kIntegerIndex,
336 shouldRunLoopAndIndexingValidation(compileOptions));
Zhenyao Mo550c6002014-02-26 15:40:48 -0800337 root->traverse(&marker);
338 }
339 if (success && (compileOptions & SH_UNROLL_FOR_LOOP_WITH_SAMPLER_ARRAY_INDEX))
Zhenyao Mo3cdfcce2014-03-07 13:00:08 -0800340 {
Olli Etuaho8a76dcc2015-12-10 20:25:12 +0200341 ForLoopUnrollMarker marker(ForLoopUnrollMarker::kSamplerArrayIndex,
342 shouldRunLoopAndIndexingValidation(compileOptions));
Zhenyao Mo550c6002014-02-26 15:40:48 -0800343 root->traverse(&marker);
344 if (marker.samplerArrayIndexIsFloatLoopIndex())
345 {
346 infoSink.info.prefix(EPrefixError);
347 infoSink.info << "sampler array index is float loop index";
348 success = false;
349 }
350 }
zmo@google.com0c6bb7a2011-08-17 19:39:58 +0000351
zmo@google.com32e97312011-08-24 01:03:11 +0000352 // Built-in function emulation needs to happen after validateLimitations pass.
Olli Etuaho8efc5ad2015-03-03 17:21:10 +0200353 if (success)
354 {
Jamie Madill438dbcf2016-06-17 14:20:05 -0400355 // TODO(jmadill): Remove global pool allocator.
356 GetGlobalPoolAllocator()->lock();
Olli Etuaho8efc5ad2015-03-03 17:21:10 +0200357 initBuiltInFunctionEmulator(&builtInFunctionEmulator, compileOptions);
Jamie Madill438dbcf2016-06-17 14:20:05 -0400358 GetGlobalPoolAllocator()->unlock();
zmo@google.com32e97312011-08-24 01:03:11 +0000359 builtInFunctionEmulator.MarkBuiltInFunctionsForEmulation(root);
Olli Etuaho8efc5ad2015-03-03 17:21:10 +0200360 }
zmo@google.com32e97312011-08-24 01:03:11 +0000361
daniel@transgaming.com4167cc92013-01-11 04:11:53 +0000362 // Clamping uniform array bounds needs to happen after validateLimitations pass.
363 if (success && (compileOptions & SH_CLAMP_INDIRECT_ARRAY_BOUNDS))
364 arrayBoundsClamper.MarkIndirectArrayBoundsForClamping(root);
365
Ian Ewell924b7de2016-01-21 13:54:28 -0500366 // gl_Position is always written in compatibility output mode
367 if (success && shaderType == GL_VERTEX_SHADER &&
368 ((compileOptions & SH_INIT_GL_POSITION) ||
369 (outputType == SH_GLSL_COMPATIBILITY_OUTPUT)))
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800370 initializeGLPosition(root);
Zhenyao Moac44cd22013-09-23 14:57:09 -0400371
Corentin Wallezd4b50542015-09-28 12:19:26 -0700372 // This pass might emit short circuits so keep it before the short circuit unfolding
373 if (success && (compileOptions & SH_REWRITE_DO_WHILE_LOOPS))
374 RewriteDoWhile(root, getTemporaryIndex());
375
Qiankun Miao09cfac62016-09-06 17:25:16 +0800376 if (success && (compileOptions & SH_ADD_AND_TRUE_TO_LOOP_CONDITION))
377 sh::AddAndTrueToLoopCondition(root);
378
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800379 if (success && (compileOptions & SH_UNFOLD_SHORT_CIRCUIT))
380 {
Zhenyao Mo7cab38b2013-10-15 12:59:30 -0700381 UnfoldShortCircuitAST unfoldShortCircuit;
382 root->traverse(&unfoldShortCircuit);
383 unfoldShortCircuit.updateTree();
384 }
385
Olli Etuaho5c407bb2015-06-01 12:20:39 +0300386 if (success && (compileOptions & SH_REMOVE_POW_WITH_CONSTANT_EXPONENT))
387 {
388 RemovePow(root);
389 }
390
Olli Etuaho4dfe8092015-08-21 17:44:35 +0300391 if (success && shouldCollectVariables(compileOptions))
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800392 {
Zhenyao Mo74da9f22013-09-23 14:57:01 -0400393 collectVariables(root);
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800394 if (compileOptions & SH_ENFORCE_PACKING_RESTRICTIONS)
395 {
gman@chromium.org8d804792012-10-17 21:33:48 +0000396 success = enforcePackingRestrictions();
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800397 if (!success)
398 {
Jamie Madill075edd82013-07-08 13:30:19 -0400399 infoSink.info.prefix(EPrefixError);
400 infoSink.info << "too many uniforms";
gman@chromium.org8d804792012-10-17 21:33:48 +0000401 }
402 }
Zhenyao Mo72111912016-07-20 17:45:56 -0700403 if (success && (compileOptions & SH_INIT_OUTPUT_VARIABLES))
404 {
Olli Etuaho27776e32016-07-22 14:00:56 +0300405 initializeOutputVariables(root);
Zhenyao Mo72111912016-07-20 17:45:56 -0700406 }
gman@chromium.org8d804792012-10-17 21:33:48 +0000407 }
zmo@google.comfd747b82011-04-23 01:30:07 +0000408
Zhenyao Mocd68fe72014-07-11 10:45:44 -0700409 if (success && (compileOptions & SH_SCALARIZE_VEC_AND_MAT_CONSTRUCTOR_ARGS))
410 {
Zhenyao Modaf56572014-08-06 16:18:30 -0700411 ScalarizeVecAndMatConstructorArgs scalarizer(
412 shaderType, fragmentPrecisionHigh);
Zhenyao Mocd68fe72014-07-11 10:45:44 -0700413 root->traverse(&scalarizer);
414 }
415
Zhenyao Moe740add2014-07-18 17:01:01 -0700416 if (success && (compileOptions & SH_REGENERATE_STRUCT_NAMES))
417 {
418 RegenerateStructNames gen(symbolTable, shaderVersion);
419 root->traverse(&gen);
420 }
Olli Etuaho3d932d82016-04-12 11:10:30 +0300421
Zhenyao Mo4e94fea2016-08-09 14:31:37 -0700422 if (success && shaderType == GL_FRAGMENT_SHADER && shaderVersion == 100 &&
423 compileResources.EXT_draw_buffers && compileResources.MaxDrawBuffers > 1 &&
424 IsExtensionEnabled(extensionBehavior, "GL_EXT_draw_buffers"))
425 {
426 EmulateGLFragColorBroadcast(root, compileResources.MaxDrawBuffers, &outputVariables);
427 }
428
Olli Etuaho3d932d82016-04-12 11:10:30 +0300429 if (success)
430 {
431 DeferGlobalInitializers(root);
432 }
alokp@chromium.org07620a52010-09-23 17:53:56 +0000433 }
434
Zhenyao Mo7faf1a12014-04-25 18:03:56 -0700435 SetGlobalParseContext(NULL);
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200436 if (success)
437 return root;
438
439 return NULL;
440}
441
Qiankun Miao7ebb97f2016-09-08 18:01:50 +0800442bool TCompiler::compile(const char *const shaderStrings[],
443 size_t numStrings,
444 ShCompileOptions compileOptionsIn)
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200445{
Corentin Wallez28b65282016-06-16 07:24:50 -0700446#if defined(ANGLE_ENABLE_FUZZER_CORPUS_OUTPUT)
447 DumpFuzzerCase(shaderStrings, numStrings, shaderType, shaderSpec, outputType, compileOptionsIn);
448#endif // defined(ANGLE_ENABLE_FUZZER_CORPUS_OUTPUT)
449
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200450 if (numStrings == 0)
451 return true;
452
Qiankun Miao7ebb97f2016-09-08 18:01:50 +0800453 ShCompileOptions compileOptions = compileOptionsIn;
Kenneth Russellbccc65d2016-07-19 16:48:43 -0700454
455 // Apply key workarounds.
456 if (shouldFlattenPragmaStdglInvariantAll())
457 {
458 // This should be harmless to do in all cases, but for the moment, do it only conditionally.
459 compileOptions |= SH_FLATTEN_PRAGMA_STDGL_INVARIANT_ALL;
460 }
461
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200462 TScopedPoolAllocator scopedAlloc(&allocator);
463 TIntermNode *root = compileTreeImpl(shaderStrings, numStrings, compileOptions);
464
465 if (root)
466 {
467 if (compileOptions & SH_INTERMEDIATE_TREE)
468 TIntermediate::outputTree(root, infoSink.info);
469
470 if (compileOptions & SH_OBJECT_CODE)
471 translate(root, compileOptions);
472
473 // The IntermNode tree doesn't need to be deleted here, since the
474 // memory will be freed in a big chunk by the PoolAllocator.
475 return true;
476 }
477 return false;
alokp@chromium.org07620a52010-09-23 17:53:56 +0000478}
479
Nicolas Capens49a88872013-06-20 09:54:03 -0400480bool TCompiler::InitBuiltInSymbolTable(const ShBuiltInResources &resources)
alokp@chromium.org07620a52010-09-23 17:53:56 +0000481{
shannon.woods%transgaming.com@gtempaccount.com18b4c4b2013-04-13 03:31:40 +0000482 compileResources = resources;
Shannon Woods2d76e5f2014-05-16 17:46:41 -0400483 setResourceString();
shannonwoods@chromium.org2ac0be92013-05-30 00:02:27 +0000484
Nicolas Capens49a88872013-06-20 09:54:03 -0400485 assert(symbolTable.isEmpty());
486 symbolTable.push(); // COMMON_BUILTINS
487 symbolTable.push(); // ESSL1_BUILTINS
488 symbolTable.push(); // ESSL3_BUILTINS
Martin Radeve93d24e2016-07-28 12:06:05 +0300489 symbolTable.push(); // ESSL3_1_BUILTINS
shannonwoods@chromium.org2ac0be92013-05-30 00:02:27 +0000490
Nicolas Capens49a88872013-06-20 09:54:03 -0400491 TPublicType integer;
Martin Radev4a9cd802016-09-01 16:51:51 +0300492 integer.setBasicType(EbtInt);
493 integer.initializeSizeForScalarTypes();
Nicolas Capens49a88872013-06-20 09:54:03 -0400494 integer.array = false;
495
496 TPublicType floatingPoint;
Martin Radev4a9cd802016-09-01 16:51:51 +0300497 floatingPoint.setBasicType(EbtFloat);
498 floatingPoint.initializeSizeForScalarTypes();
Nicolas Capens49a88872013-06-20 09:54:03 -0400499 floatingPoint.array = false;
500
501 switch(shaderType)
502 {
Jamie Madill183bde52014-07-02 15:31:19 -0400503 case GL_FRAGMENT_SHADER:
Nicolas Capens49a88872013-06-20 09:54:03 -0400504 symbolTable.setDefaultPrecision(integer, EbpMedium);
505 break;
Jamie Madill183bde52014-07-02 15:31:19 -0400506 case GL_VERTEX_SHADER:
Nicolas Capens49a88872013-06-20 09:54:03 -0400507 symbolTable.setDefaultPrecision(integer, EbpHigh);
508 symbolTable.setDefaultPrecision(floatingPoint, EbpHigh);
509 break;
Martin Radev802abe02016-08-04 17:48:32 +0300510 case GL_COMPUTE_SHADER:
511 symbolTable.setDefaultPrecision(integer, EbpHigh);
512 symbolTable.setDefaultPrecision(floatingPoint, EbpHigh);
513 break;
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800514 default:
515 assert(false && "Language not supported");
Nicolas Capens49a88872013-06-20 09:54:03 -0400516 }
Olli Etuaho183d7e22015-11-20 15:59:09 +0200517 // Set defaults for sampler types that have default precision, even those that are
Zhenyao Moa5a1dfc2013-09-23 14:57:03 -0400518 // only available if an extension exists.
Olli Etuaho183d7e22015-11-20 15:59:09 +0200519 // New sampler types in ESSL3 don't have default precision. ESSL1 types do.
520 initSamplerDefaultPrecision(EbtSampler2D);
521 initSamplerDefaultPrecision(EbtSamplerCube);
522 // SamplerExternalOES is specified in the extension to have default precision.
523 initSamplerDefaultPrecision(EbtSamplerExternalOES);
524 // It isn't specified whether Sampler2DRect has default precision.
525 initSamplerDefaultPrecision(EbtSampler2DRect);
Nicolas Capens49a88872013-06-20 09:54:03 -0400526
Jamie Madill1b452142013-07-12 14:51:11 -0400527 InsertBuiltInFunctions(shaderType, shaderSpec, resources, symbolTable);
Nicolas Capens49a88872013-06-20 09:54:03 -0400528
529 IdentifyBuiltIns(shaderType, shaderSpec, resources, symbolTable);
530
531 return true;
alokp@chromium.org07620a52010-09-23 17:53:56 +0000532}
533
Olli Etuaho183d7e22015-11-20 15:59:09 +0200534void TCompiler::initSamplerDefaultPrecision(TBasicType samplerType)
535{
536 ASSERT(samplerType > EbtGuardSamplerBegin && samplerType < EbtGuardSamplerEnd);
537 TPublicType sampler;
Martin Radev4a9cd802016-09-01 16:51:51 +0300538 sampler.initializeSizeForScalarTypes();
539 sampler.setBasicType(samplerType);
Olli Etuaho183d7e22015-11-20 15:59:09 +0200540 sampler.array = false;
Olli Etuaho183d7e22015-11-20 15:59:09 +0200541 symbolTable.setDefaultPrecision(sampler, EbpLow);
542}
543
Shannon Woods2d76e5f2014-05-16 17:46:41 -0400544void TCompiler::setResourceString()
545{
546 std::ostringstream strstream;
Geoff Langb66a9092016-05-16 15:59:14 -0400547
548 // clang-format off
Shannon Woods2d76e5f2014-05-16 17:46:41 -0400549 strstream << ":MaxVertexAttribs:" << compileResources.MaxVertexAttribs
550 << ":MaxVertexUniformVectors:" << compileResources.MaxVertexUniformVectors
551 << ":MaxVaryingVectors:" << compileResources.MaxVaryingVectors
552 << ":MaxVertexTextureImageUnits:" << compileResources.MaxVertexTextureImageUnits
553 << ":MaxCombinedTextureImageUnits:" << compileResources.MaxCombinedTextureImageUnits
554 << ":MaxTextureImageUnits:" << compileResources.MaxTextureImageUnits
555 << ":MaxFragmentUniformVectors:" << compileResources.MaxFragmentUniformVectors
556 << ":MaxDrawBuffers:" << compileResources.MaxDrawBuffers
557 << ":OES_standard_derivatives:" << compileResources.OES_standard_derivatives
558 << ":OES_EGL_image_external:" << compileResources.OES_EGL_image_external
Geoff Langb66a9092016-05-16 15:59:14 -0400559 << ":OES_EGL_image_external_essl3:" << compileResources.OES_EGL_image_external_essl3
560 << ":NV_EGL_stream_consumer_external:" << compileResources.NV_EGL_stream_consumer_external
Shannon Woods2d76e5f2014-05-16 17:46:41 -0400561 << ":ARB_texture_rectangle:" << compileResources.ARB_texture_rectangle
562 << ":EXT_draw_buffers:" << compileResources.EXT_draw_buffers
563 << ":FragmentPrecisionHigh:" << compileResources.FragmentPrecisionHigh
564 << ":MaxExpressionComplexity:" << compileResources.MaxExpressionComplexity
565 << ":MaxCallStackDepth:" << compileResources.MaxCallStackDepth
Olli Etuaho19d1dc92016-03-08 17:18:46 +0200566 << ":MaxFunctionParameters:" << compileResources.MaxFunctionParameters
Kimmo Kinnunenb18609b2015-07-16 14:13:11 +0300567 << ":EXT_blend_func_extended:" << compileResources.EXT_blend_func_extended
Shannon Woods2d76e5f2014-05-16 17:46:41 -0400568 << ":EXT_frag_depth:" << compileResources.EXT_frag_depth
569 << ":EXT_shader_texture_lod:" << compileResources.EXT_shader_texture_lod
Erik Dahlströmea7a2122014-11-17 16:15:57 +0100570 << ":EXT_shader_framebuffer_fetch:" << compileResources.EXT_shader_framebuffer_fetch
571 << ":NV_shader_framebuffer_fetch:" << compileResources.NV_shader_framebuffer_fetch
572 << ":ARM_shader_framebuffer_fetch:" << compileResources.ARM_shader_framebuffer_fetch
Shannon Woods2d76e5f2014-05-16 17:46:41 -0400573 << ":MaxVertexOutputVectors:" << compileResources.MaxVertexOutputVectors
574 << ":MaxFragmentInputVectors:" << compileResources.MaxFragmentInputVectors
575 << ":MinProgramTexelOffset:" << compileResources.MinProgramTexelOffset
Olli Etuahoe61209a2014-09-26 12:01:17 +0300576 << ":MaxProgramTexelOffset:" << compileResources.MaxProgramTexelOffset
Kimmo Kinnunenb18609b2015-07-16 14:13:11 +0300577 << ":MaxDualSourceDrawBuffers:" << compileResources.MaxDualSourceDrawBuffers
Olli Etuaho853dc1a2014-11-06 17:25:48 +0200578 << ":NV_draw_buffers:" << compileResources.NV_draw_buffers
Martin Radeve93d24e2016-07-28 12:06:05 +0300579 << ":WEBGL_debug_shader_precision:" << compileResources.WEBGL_debug_shader_precision
580 << ":MaxImageUnits:" << compileResources.MaxImageUnits
581 << ":MaxVertexImageUniforms:" << compileResources.MaxVertexImageUniforms
582 << ":MaxFragmentImageUniforms:" << compileResources.MaxFragmentImageUniforms
583 << ":MaxComputeImageUniforms:" << compileResources.MaxComputeImageUniforms
584 << ":MaxCombinedImageUniforms:" << compileResources.MaxCombinedImageUniforms
585 << ":MaxCombinedShaderOutputResources:" << compileResources.MaxCombinedShaderOutputResources
586 << ":MaxComputeWorkGroupCountX:" << compileResources.MaxComputeWorkGroupCount[0]
587 << ":MaxComputeWorkGroupCountY:" << compileResources.MaxComputeWorkGroupCount[1]
588 << ":MaxComputeWorkGroupCountZ:" << compileResources.MaxComputeWorkGroupCount[2]
589 << ":MaxComputeWorkGroupSizeX:" << compileResources.MaxComputeWorkGroupSize[0]
590 << ":MaxComputeWorkGroupSizeY:" << compileResources.MaxComputeWorkGroupSize[1]
591 << ":MaxComputeWorkGroupSizeZ:" << compileResources.MaxComputeWorkGroupSize[2]
592 << ":MaxComputeUniformComponents:" << compileResources.MaxComputeUniformComponents
593 << ":MaxComputeTextureImageUnits:" << compileResources.MaxComputeTextureImageUnits
594 << ":MaxComputeAtomicCounters:" << compileResources.MaxComputeAtomicCounters
595 << ":MaxComputeAtomicCounterBuffers:" << compileResources.MaxComputeAtomicCounterBuffers
596 << ":MaxVertexAtomicCounters:" << compileResources.MaxVertexAtomicCounters
597 << ":MaxFragmentAtomicCounters:" << compileResources.MaxFragmentAtomicCounters
598 << ":MaxCombinedAtomicCounters:" << compileResources.MaxCombinedAtomicCounters
599 << ":MaxAtomicCounterBindings:" << compileResources.MaxAtomicCounterBindings
600 << ":MaxVertexAtomicCounterBuffers:" << compileResources.MaxVertexAtomicCounterBuffers
601 << ":MaxFragmentAtomicCounterBuffers:" << compileResources.MaxFragmentAtomicCounterBuffers
602 << ":MaxCombinedAtomicCounterBuffers:" << compileResources.MaxCombinedAtomicCounterBuffers
603 << ":MaxAtomicCounterBufferSize:" << compileResources.MaxAtomicCounterBufferSize;
Geoff Langb66a9092016-05-16 15:59:14 -0400604 // clang-format on
Shannon Woods2d76e5f2014-05-16 17:46:41 -0400605
606 builtInResourcesString = strstream.str();
607}
608
alokp@chromium.org07620a52010-09-23 17:53:56 +0000609void TCompiler::clearResults()
610{
daniel@transgaming.com4167cc92013-01-11 04:11:53 +0000611 arrayBoundsClamper.Cleanup();
alokp@chromium.org07620a52010-09-23 17:53:56 +0000612 infoSink.info.erase();
613 infoSink.obj.erase();
614 infoSink.debug.erase();
615
Jamie Madilled27c722014-07-02 15:31:23 -0400616 attributes.clear();
617 outputVariables.clear();
alokp@chromium.org07620a52010-09-23 17:53:56 +0000618 uniforms.clear();
Jamie Madill23a8a432014-07-09 13:27:42 -0400619 expandedUniforms.clear();
Zhenyao Mod2d340b2013-09-23 14:57:05 -0400620 varyings.clear();
Jamie Madilled27c722014-07-02 15:31:23 -0400621 interfaceBlocks.clear();
Kenneth Russellbccc65d2016-07-19 16:48:43 -0700622 variablesCollected = false;
zmo@google.coma3b4ab42011-09-16 00:53:26 +0000623
624 builtInFunctionEmulator.Cleanup();
daniel@transgaming.com0aa3b5a2012-11-28 19:43:24 +0000625
626 nameMap.clear();
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200627
628 mSourcePath = NULL;
Corentin Wallezd4b50542015-09-28 12:19:26 -0700629 mTemporaryIndex = 0;
alokp@chromium.org07620a52010-09-23 17:53:56 +0000630}
631
Corentin Wallez71d147f2015-02-11 11:15:24 -0800632bool TCompiler::initCallDag(TIntermNode *root)
zmo@google.comb1762df2011-07-30 02:04:23 +0000633{
Corentin Wallez71d147f2015-02-11 11:15:24 -0800634 mCallDag.clear();
635
636 switch (mCallDag.init(root, &infoSink.info))
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800637 {
Corentin Wallez71d147f2015-02-11 11:15:24 -0800638 case CallDAG::INITDAG_SUCCESS:
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800639 return true;
Corentin Wallez71d147f2015-02-11 11:15:24 -0800640 case CallDAG::INITDAG_RECURSION:
641 infoSink.info.prefix(EPrefixError);
642 infoSink.info << "Function recursion detected";
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800643 return false;
Corentin Wallez71d147f2015-02-11 11:15:24 -0800644 case CallDAG::INITDAG_UNDEFINED:
645 infoSink.info.prefix(EPrefixError);
646 infoSink.info << "Unimplemented function detected";
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800647 return false;
Corentin Wallez71d147f2015-02-11 11:15:24 -0800648 }
649
650 UNREACHABLE();
651 return true;
652}
653
654bool TCompiler::checkCallDepth()
655{
656 std::vector<int> depths(mCallDag.size());
657
658 for (size_t i = 0; i < mCallDag.size(); i++)
659 {
660 int depth = 0;
661 auto &record = mCallDag.getRecordFromIndex(i);
662
663 for (auto &calleeIndex : record.callees)
664 {
665 depth = std::max(depth, depths[calleeIndex] + 1);
666 }
667
668 depths[i] = depth;
669
670 if (depth >= maxCallStackDepth)
671 {
672 // Trace back the function chain to have a meaningful info log.
673 infoSink.info.prefix(EPrefixError);
674 infoSink.info << "Call stack too deep (larger than " << maxCallStackDepth
675 << ") with the following call chain: " << record.name;
676
Cooper Partin4d61f7e2015-08-12 10:56:50 -0700677 int currentFunction = static_cast<int>(i);
Corentin Wallez71d147f2015-02-11 11:15:24 -0800678 int currentDepth = depth;
679
680 while (currentFunction != -1)
681 {
682 infoSink.info << " -> " << mCallDag.getRecordFromIndex(currentFunction).name;
683
684 int nextFunction = -1;
685 for (auto& calleeIndex : mCallDag.getRecordFromIndex(currentFunction).callees)
686 {
687 if (depths[calleeIndex] == currentDepth - 1)
688 {
689 currentDepth--;
690 nextFunction = calleeIndex;
691 }
692 }
693
694 currentFunction = nextFunction;
695 }
696
697 return false;
698 }
699 }
700
701 return true;
702}
703
704bool TCompiler::tagUsedFunctions()
705{
706 // Search from main, starting from the end of the DAG as it usually is the root.
Cooper Partin4d61f7e2015-08-12 10:56:50 -0700707 for (size_t i = mCallDag.size(); i-- > 0;)
Corentin Wallez71d147f2015-02-11 11:15:24 -0800708 {
709 if (mCallDag.getRecordFromIndex(i).name == "main(")
710 {
711 internalTagUsedFunction(i);
712 return true;
713 }
714 }
715
716 infoSink.info.prefix(EPrefixError);
Olli Etuaho792a41d2015-12-15 12:39:16 +0200717 infoSink.info << "Missing main()\n";
Corentin Wallez71d147f2015-02-11 11:15:24 -0800718 return false;
719}
720
721void TCompiler::internalTagUsedFunction(size_t index)
722{
723 if (functionMetadata[index].used)
724 {
725 return;
726 }
727
728 functionMetadata[index].used = true;
729
730 for (int calleeIndex : mCallDag.getRecordFromIndex(index).callees)
731 {
732 internalTagUsedFunction(calleeIndex);
zmo@google.comb1762df2011-07-30 02:04:23 +0000733 }
734}
735
Corentin Walleza094a8a2015-04-07 11:53:06 -0700736// A predicate for the stl that returns if a top-level node is unused
737class TCompiler::UnusedPredicate
738{
739 public:
740 UnusedPredicate(const CallDAG *callDag, const std::vector<FunctionMetadata> *metadatas)
741 : mCallDag(callDag),
742 mMetadatas(metadatas)
743 {
744 }
745
746 bool operator ()(TIntermNode *node)
747 {
748 const TIntermAggregate *asAggregate = node->getAsAggregate();
749
750 if (asAggregate == nullptr)
751 {
752 return false;
753 }
754
755 if (!(asAggregate->getOp() == EOpFunction || asAggregate->getOp() == EOpPrototype))
756 {
757 return false;
758 }
759
760 size_t callDagIndex = mCallDag->findIndex(asAggregate);
761 if (callDagIndex == CallDAG::InvalidIndex)
762 {
763 // This happens only for unimplemented prototypes which are thus unused
764 ASSERT(asAggregate->getOp() == EOpPrototype);
765 return true;
766 }
767
768 ASSERT(callDagIndex < mMetadatas->size());
769 return !(*mMetadatas)[callDagIndex].used;
770 }
771
772 private:
773 const CallDAG *mCallDag;
774 const std::vector<FunctionMetadata> *mMetadatas;
775};
776
777bool TCompiler::pruneUnusedFunctions(TIntermNode *root)
778{
779 TIntermAggregate *rootNode = root->getAsAggregate();
780 ASSERT(rootNode != nullptr);
781
782 UnusedPredicate isUnused(&mCallDag, &functionMetadata);
783 TIntermSequence *sequence = rootNode->getSequence();
Corentin Wallezb081e782015-07-20 05:40:04 -0700784
785 if (!sequence->empty())
786 {
787 sequence->erase(std::remove_if(sequence->begin(), sequence->end(), isUnused), sequence->end());
788 }
Corentin Walleza094a8a2015-04-07 11:53:06 -0700789
790 return true;
791}
792
Jamie Madill05a80ce2013-06-20 11:55:49 -0400793bool TCompiler::validateOutputs(TIntermNode* root)
794{
Kimmo Kinnunenb18609b2015-07-16 14:13:11 +0300795 ValidateOutputs validateOutputs(getExtensionBehavior(), compileResources.MaxDrawBuffers);
Jamie Madill05a80ce2013-06-20 11:55:49 -0400796 root->traverse(&validateOutputs);
Kimmo Kinnunenb18609b2015-07-16 14:13:11 +0300797 return (validateOutputs.validateAndCountErrors(infoSink.info) == 0);
Jamie Madill05a80ce2013-06-20 11:55:49 -0400798}
799
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800800bool TCompiler::validateLimitations(TIntermNode* root)
801{
Olli Etuaho8a76dcc2015-12-10 20:25:12 +0200802 ValidateLimitations validate(shaderType, &infoSink.info);
alokp@chromium.orgb59a7782010-11-24 18:38:33 +0000803 root->traverse(&validate);
804 return validate.numErrors() == 0;
805}
806
Jamie Madilleb1a0102013-07-08 13:31:38 -0400807bool TCompiler::limitExpressionComplexity(TIntermNode* root)
808{
Jamie Madill6654bc92014-03-26 14:01:57 -0400809 TMaxDepthTraverser traverser(maxExpressionComplexity+1);
Jamie Madilleb1a0102013-07-08 13:31:38 -0400810 root->traverse(&traverser);
Jamie Madill6654bc92014-03-26 14:01:57 -0400811
812 if (traverser.getMaxDepth() > maxExpressionComplexity)
813 {
814 infoSink.info << "Expression too complex.";
815 return false;
816 }
817
Olli Etuaho19d1dc92016-03-08 17:18:46 +0200818 if (!ValidateMaxParameters::validate(root, maxFunctionParameters))
819 {
820 infoSink.info << "Function has too many parameters.";
821 return false;
822 }
823
Jamie Madilleb1a0102013-07-08 13:31:38 -0400824 return true;
825}
826
Zhenyao Mo74da9f22013-09-23 14:57:01 -0400827void TCompiler::collectVariables(TIntermNode* root)
alokp@chromium.org07620a52010-09-23 17:53:56 +0000828{
Kenneth Russellbccc65d2016-07-19 16:48:43 -0700829 if (!variablesCollected)
830 {
831 sh::CollectVariables collect(&attributes, &outputVariables, &uniforms, &varyings,
832 &interfaceBlocks, hashFunction, symbolTable, extensionBehavior);
833 root->traverse(&collect);
Jamie Madill23a8a432014-07-09 13:27:42 -0400834
Kenneth Russellbccc65d2016-07-19 16:48:43 -0700835 // This is for enforcePackingRestriction().
836 sh::ExpandUniforms(uniforms, &expandedUniforms);
837 variablesCollected = true;
838 }
alokp@chromium.org07620a52010-09-23 17:53:56 +0000839}
zmo@google.comfd747b82011-04-23 01:30:07 +0000840
gman@chromium.org8d804792012-10-17 21:33:48 +0000841bool TCompiler::enforcePackingRestrictions()
842{
843 VariablePacker packer;
Jamie Madill23a8a432014-07-09 13:27:42 -0400844 return packer.CheckVariablesWithinPackingLimits(maxUniformVectors, expandedUniforms);
gman@chromium.org8d804792012-10-17 21:33:48 +0000845}
846
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800847void TCompiler::initializeGLPosition(TIntermNode* root)
848{
Zhenyao Mo72111912016-07-20 17:45:56 -0700849 InitVariableList list;
850 sh::ShaderVariable var(GL_FLOAT_VEC4, 0);
851 var.name = "gl_Position";
852 list.push_back(var);
853 InitializeVariables(root, list);
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800854}
855
Olli Etuaho27776e32016-07-22 14:00:56 +0300856void TCompiler::initializeOutputVariables(TIntermNode *root)
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800857{
Zhenyao Mo72111912016-07-20 17:45:56 -0700858 InitVariableList list;
859 if (shaderType == GL_VERTEX_SHADER)
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800860 {
Zhenyao Mo72111912016-07-20 17:45:56 -0700861 for (auto var : varyings)
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800862 {
Zhenyao Mof9312682016-07-22 12:51:31 -0700863 list.push_back(var);
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800864 }
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800865 }
Zhenyao Mo72111912016-07-20 17:45:56 -0700866 else
867 {
868 ASSERT(shaderType == GL_FRAGMENT_SHADER);
869 for (auto var : outputVariables)
870 {
871 list.push_back(var);
872 }
873 }
874 InitializeVariables(root, list);
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800875}
876
zmo@google.com5601ea02011-06-10 18:23:25 +0000877const TExtensionBehavior& TCompiler::getExtensionBehavior() const
878{
879 return extensionBehavior;
880}
zmo@google.com32e97312011-08-24 01:03:11 +0000881
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200882const char *TCompiler::getSourcePath() const
883{
884 return mSourcePath;
885}
886
shannon.woods%transgaming.com@gtempaccount.com18b4c4b2013-04-13 03:31:40 +0000887const ShBuiltInResources& TCompiler::getResources() const
888{
889 return compileResources;
890}
891
daniel@transgaming.com4167cc92013-01-11 04:11:53 +0000892const ArrayBoundsClamper& TCompiler::getArrayBoundsClamper() const
893{
894 return arrayBoundsClamper;
895}
896
shannon.woods@transgaming.com1d432bb2013-01-25 21:57:28 +0000897ShArrayIndexClampingStrategy TCompiler::getArrayIndexClampingStrategy() const
898{
899 return clampingStrategy;
900}
901
Olli Etuaho8efc5ad2015-03-03 17:21:10 +0200902const BuiltInFunctionEmulator& TCompiler::getBuiltInFunctionEmulator() const
shannon.woods@transgaming.com1d432bb2013-01-25 21:57:28 +0000903{
904 return builtInFunctionEmulator;
905}
Zhenyao Mo94ac7b72014-10-15 18:22:08 -0700906
Qiankun Miao7ebb97f2016-09-08 18:01:50 +0800907void TCompiler::writePragma(ShCompileOptions compileOptions)
Zhenyao Mo94ac7b72014-10-15 18:22:08 -0700908{
Kenneth Russellbccc65d2016-07-19 16:48:43 -0700909 if (!(compileOptions & SH_FLATTEN_PRAGMA_STDGL_INVARIANT_ALL))
910 {
911 TInfoSinkBase &sink = infoSink.obj;
912 if (mPragma.stdgl.invariantAll)
913 sink << "#pragma STDGL invariant(all)\n";
914 }
915}
916
917bool TCompiler::isVaryingDefined(const char *varyingName)
918{
919 ASSERT(variablesCollected);
920 for (size_t ii = 0; ii < varyings.size(); ++ii)
921 {
922 if (varyings[ii].name == varyingName)
923 {
924 return true;
925 }
926 }
927
928 return false;
Zhenyao Mo94ac7b72014-10-15 18:22:08 -0700929}