blob: 8b5b12f9568698a4808ecd089e32fe0835855d63 [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
Jamie Madilld4a3a312014-06-25 16:04:56 -04007#include "compiler/translator/Compiler.h"
Corentin Wallez71d147f2015-02-11 11:15:24 -08008#include "compiler/translator/CallDAG.h"
Geoff Lang17732822013-08-29 13:46:49 -04009#include "compiler/translator/ForLoopUnroll.h"
10#include "compiler/translator/Initialize.h"
Geoff Lang17732822013-08-29 13:46:49 -040011#include "compiler/translator/InitializeParseContext.h"
Zhenyao Mo4a667fe2014-02-11 12:35:01 -080012#include "compiler/translator/InitializeVariables.h"
Jamie Madill6b9cb252013-10-17 10:45:47 -040013#include "compiler/translator/ParseContext.h"
Olli Etuahoc6833112015-04-22 15:15:54 +030014#include "compiler/translator/PruneEmptyDeclarations.h"
Zhenyao Moe740add2014-07-18 17:01:01 -070015#include "compiler/translator/RegenerateStructNames.h"
Geoff Lang17732822013-08-29 13:46:49 -040016#include "compiler/translator/RenameFunction.h"
Zhenyao Mocd68fe72014-07-11 10:45:44 -070017#include "compiler/translator/ScalarizeVecAndMatConstructorArgs.h"
Zhenyao Mo7cab38b2013-10-15 12:59:30 -070018#include "compiler/translator/UnfoldShortCircuitAST.h"
Geoff Lang17732822013-08-29 13:46:49 -040019#include "compiler/translator/ValidateLimitations.h"
20#include "compiler/translator/ValidateOutputs.h"
21#include "compiler/translator/VariablePacker.h"
22#include "compiler/translator/depgraph/DependencyGraph.h"
23#include "compiler/translator/depgraph/DependencyGraphOutput.h"
24#include "compiler/translator/timing/RestrictFragmentShaderTiming.h"
25#include "compiler/translator/timing/RestrictVertexShaderTiming.h"
shannon.woods@transgaming.comda1ed362013-01-25 21:54:57 +000026#include "third_party/compiler/ArrayBoundsClamper.h"
Jamie Madill183bde52014-07-02 15:31:19 -040027#include "angle_gl.h"
Jamie Madillaa72d782014-07-02 15:31:19 -040028#include "common/utilities.h"
alokp@chromium.org07620a52010-09-23 17:53:56 +000029
Jamie Madill5508f392014-02-20 13:31:36 -050030bool IsWebGLBasedSpec(ShShaderSpec spec)
maxvujovic@gmail.com430f5e02012-06-08 17:47:59 +000031{
Zhenyao Modb9b40b2014-10-29 15:00:04 -070032 return (spec == SH_WEBGL_SPEC ||
33 spec == SH_CSS_SHADERS_SPEC ||
34 spec == SH_WEBGL2_SPEC);
maxvujovic@gmail.com430f5e02012-06-08 17:47:59 +000035}
36
Qingqing Dengad0d0792015-04-08 14:25:06 -070037bool IsGLSL130OrNewer(ShShaderOutput output)
38{
39 return (output == SH_GLSL_130_OUTPUT ||
40 output == SH_GLSL_410_CORE_OUTPUT ||
41 output == SH_GLSL_420_CORE_OUTPUT);
42}
43
Zhenyao Mo7faf1a12014-04-25 18:03:56 -070044size_t GetGlobalMaxTokenSize(ShShaderSpec spec)
Jamie Madill88f6e942014-02-19 10:27:53 -050045{
Jamie Madill88f6e942014-02-19 10:27:53 -050046 // WebGL defines a max token legnth of 256, while ES2 leaves max token
47 // size undefined. ES3 defines a max size of 1024 characters.
Zhenyao Modb9b40b2014-10-29 15:00:04 -070048 switch (spec)
Jamie Madill88f6e942014-02-19 10:27:53 -050049 {
Zhenyao Modb9b40b2014-10-29 15:00:04 -070050 case SH_WEBGL_SPEC:
51 case SH_CSS_SHADERS_SPEC:
Jamie Madill88f6e942014-02-19 10:27:53 -050052 return 256;
Zhenyao Modb9b40b2014-10-29 15:00:04 -070053 default:
Jamie Madill88f6e942014-02-19 10:27:53 -050054 return 1024;
55 }
56}
57
alokp@chromium.orgbafcbaa2010-11-23 19:07:43 +000058namespace {
Zhenyao Modb9b40b2014-10-29 15:00:04 -070059
Zhenyao Mo4a667fe2014-02-11 12:35:01 -080060class TScopedPoolAllocator
61{
62 public:
63 TScopedPoolAllocator(TPoolAllocator* allocator) : mAllocator(allocator)
64 {
Alok Priyadarshibc3f1ac2013-09-23 14:57:02 -040065 mAllocator->push();
alokp@chromium.orgbafcbaa2010-11-23 19:07:43 +000066 SetGlobalPoolAllocator(mAllocator);
67 }
Zhenyao Mo4a667fe2014-02-11 12:35:01 -080068 ~TScopedPoolAllocator()
69 {
alokp@chromium.orgbafcbaa2010-11-23 19:07:43 +000070 SetGlobalPoolAllocator(NULL);
Alok Priyadarshibc3f1ac2013-09-23 14:57:02 -040071 mAllocator->pop();
alokp@chromium.orgbafcbaa2010-11-23 19:07:43 +000072 }
73
Zhenyao Mo4a667fe2014-02-11 12:35:01 -080074 private:
alokp@chromium.orgbafcbaa2010-11-23 19:07:43 +000075 TPoolAllocator* mAllocator;
Alok Priyadarshibc3f1ac2013-09-23 14:57:02 -040076};
77
Zhenyao Mo4a667fe2014-02-11 12:35:01 -080078class TScopedSymbolTableLevel
79{
80 public:
81 TScopedSymbolTableLevel(TSymbolTable* table) : mTable(table)
82 {
Alok Priyadarshibc3f1ac2013-09-23 14:57:02 -040083 ASSERT(mTable->atBuiltInLevel());
84 mTable->push();
85 }
Zhenyao Mo4a667fe2014-02-11 12:35:01 -080086 ~TScopedSymbolTableLevel()
87 {
Alok Priyadarshibc3f1ac2013-09-23 14:57:02 -040088 while (!mTable->atBuiltInLevel())
89 mTable->pop();
90 }
91
Zhenyao Mo4a667fe2014-02-11 12:35:01 -080092 private:
Alok Priyadarshibc3f1ac2013-09-23 14:57:02 -040093 TSymbolTable* mTable;
alokp@chromium.orgbafcbaa2010-11-23 19:07:43 +000094};
Zhenyao Modb9b40b2014-10-29 15:00:04 -070095
96int MapSpecToShaderVersion(ShShaderSpec spec)
97{
98 switch (spec)
99 {
100 case SH_GLES2_SPEC:
101 case SH_WEBGL_SPEC:
102 case SH_CSS_SHADERS_SPEC:
103 return 100;
104 case SH_GLES3_SPEC:
105 case SH_WEBGL2_SPEC:
106 return 300;
107 default:
108 UNREACHABLE();
109 return 0;
110 }
111}
112
alokp@chromium.orgbafcbaa2010-11-23 19:07:43 +0000113} // namespace
114
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800115TShHandleBase::TShHandleBase()
116{
alokp@chromium.orgbafcbaa2010-11-23 19:07:43 +0000117 allocator.push();
118 SetGlobalPoolAllocator(&allocator);
119}
120
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800121TShHandleBase::~TShHandleBase()
122{
alokp@chromium.orgbafcbaa2010-11-23 19:07:43 +0000123 SetGlobalPoolAllocator(NULL);
124 allocator.popAll();
125}
126
Jamie Madill183bde52014-07-02 15:31:19 -0400127TCompiler::TCompiler(sh::GLenum type, ShShaderSpec spec, ShShaderOutput output)
alokp@chromium.org4888ceb2010-10-01 21:13:12 +0000128 : shaderType(type),
zmo@google.comf420c422011-09-12 18:27:59 +0000129 shaderSpec(spec),
Jamie Madill68fe74a2014-05-27 12:56:01 -0400130 outputType(output),
Jamie Madilleb1a0102013-07-08 13:31:38 -0400131 maxUniformVectors(0),
132 maxExpressionComplexity(0),
133 maxCallStackDepth(0),
shannon.woods%transgaming.com@gtempaccount.comcbb6b6a2013-04-13 03:27:47 +0000134 fragmentPrecisionHigh(false),
shannon.woods@transgaming.com1d432bb2013-01-25 21:57:28 +0000135 clampingStrategy(SH_CLAMP_WITH_CLAMP_INTRINSIC),
Olli Etuaho8efc5ad2015-03-03 17:21:10 +0200136 builtInFunctionEmulator(),
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200137 mSourcePath(NULL)
alokp@chromium.org4888ceb2010-10-01 21:13:12 +0000138{
139}
140
141TCompiler::~TCompiler()
142{
143}
144
145bool TCompiler::Init(const ShBuiltInResources& resources)
alokp@chromium.org07620a52010-09-23 17:53:56 +0000146{
shannon.woods%transgaming.com@gtempaccount.com0bbed382013-04-13 03:38:07 +0000147 shaderVersion = 100;
Jamie Madill183bde52014-07-02 15:31:19 -0400148 maxUniformVectors = (shaderType == GL_VERTEX_SHADER) ?
gman@chromium.org8d804792012-10-17 21:33:48 +0000149 resources.MaxVertexUniformVectors :
150 resources.MaxFragmentUniformVectors;
Jamie Madilleb1a0102013-07-08 13:31:38 -0400151 maxExpressionComplexity = resources.MaxExpressionComplexity;
152 maxCallStackDepth = resources.MaxCallStackDepth;
Alok Priyadarshibc3f1ac2013-09-23 14:57:02 -0400153
154 SetGlobalPoolAllocator(&allocator);
alokp@chromium.orgbafcbaa2010-11-23 19:07:43 +0000155
alokp@chromium.org07620a52010-09-23 17:53:56 +0000156 // Generate built-in symbol table.
157 if (!InitBuiltInSymbolTable(resources))
158 return false;
alokp@chromium.org07620a52010-09-23 17:53:56 +0000159 InitExtensionBehavior(resources, extensionBehavior);
shannon.woods%transgaming.com@gtempaccount.comcbb6b6a2013-04-13 03:27:47 +0000160 fragmentPrecisionHigh = resources.FragmentPrecisionHigh == 1;
alokp@chromium.orgbafcbaa2010-11-23 19:07:43 +0000161
shannon.woods@transgaming.com1d432bb2013-01-25 21:57:28 +0000162 arrayBoundsClamper.SetClampingStrategy(resources.ArrayIndexClampingStrategy);
163 clampingStrategy = resources.ArrayIndexClampingStrategy;
164
daniel@transgaming.comc23f4612012-11-28 19:42:57 +0000165 hashFunction = resources.HashFunction;
166
alokp@chromium.org07620a52010-09-23 17:53:56 +0000167 return true;
168}
169
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200170TIntermNode *TCompiler::compileTreeForTesting(const char* const shaderStrings[],
171 size_t numStrings, int compileOptions)
alokp@chromium.org07620a52010-09-23 17:53:56 +0000172{
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200173 return compileTreeImpl(shaderStrings, numStrings, compileOptions);
174}
175
176TIntermNode *TCompiler::compileTreeImpl(const char* const shaderStrings[],
177 size_t numStrings, int compileOptions)
178{
alokp@chromium.org07620a52010-09-23 17:53:56 +0000179 clearResults();
180
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200181 ASSERT(numStrings > 0);
182 ASSERT(GetGlobalPoolAllocator());
alokp@chromium.org07620a52010-09-23 17:53:56 +0000183
David Yen0fbd1282015-02-02 14:46:09 -0800184 // Reset the extension behavior for each compilation unit.
185 ResetExtensionBehavior(extensionBehavior);
186
alokp@chromium.orgb59a7782010-11-24 18:38:33 +0000187 // If compiling for WebGL, validate loop and indexing as well.
Jamie Madill5508f392014-02-20 13:31:36 -0500188 if (IsWebGLBasedSpec(shaderSpec))
alokp@chromium.orgb59a7782010-11-24 18:38:33 +0000189 compileOptions |= SH_VALIDATE_LOOP_INDEXING;
alokp@chromium.org1f299542010-11-12 15:50:23 +0000190
apatrick@chromium.org0f4cefe2011-01-26 19:30:57 +0000191 // First string is path of source file if flag is set. The actual source follows.
shannon.woods@transgaming.comd64b3da2013-02-28 23:19:26 +0000192 size_t firstSource = 0;
apatrick@chromium.org0f4cefe2011-01-26 19:30:57 +0000193 if (compileOptions & SH_SOURCE_PATH)
194 {
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200195 mSourcePath = shaderStrings[0];
apatrick@chromium.org0f4cefe2011-01-26 19:30:57 +0000196 ++firstSource;
197 }
198
Olli Etuaho853dc1a2014-11-06 17:25:48 +0200199 bool debugShaderPrecision = getResources().WEBGL_debug_shader_precision == 1;
alokp@chromium.org07620a52010-09-23 17:53:56 +0000200 TIntermediate intermediate(infoSink);
201 TParseContext parseContext(symbolTable, extensionBehavior, intermediate,
zmo@google.comdc4b4f82011-06-17 00:42:53 +0000202 shaderType, shaderSpec, compileOptions, true,
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200203 infoSink, debugShaderPrecision);
Olli Etuaho853dc1a2014-11-06 17:25:48 +0200204
shannon.woods%transgaming.com@gtempaccount.comcbb6b6a2013-04-13 03:27:47 +0000205 parseContext.fragmentPrecisionHigh = fragmentPrecisionHigh;
Alok Priyadarshi8156b6b2013-09-23 14:56:58 -0400206 SetGlobalParseContext(&parseContext);
alokp@chromium.org07620a52010-09-23 17:53:56 +0000207
208 // We preserve symbols at the built-in level from compile-to-compile.
209 // Start pushing the user-defined symbols at global level.
Alok Priyadarshibc3f1ac2013-09-23 14:57:02 -0400210 TScopedSymbolTableLevel scopedSymbolLevel(&symbolTable);
alokp@chromium.org07620a52010-09-23 17:53:56 +0000211
212 // Parse shader.
213 bool success =
apatrick@chromium.org0f4cefe2011-01-26 19:30:57 +0000214 (PaParseStrings(numStrings - firstSource, &shaderStrings[firstSource], NULL, &parseContext) == 0) &&
alokp@chromium.org07620a52010-09-23 17:53:56 +0000215 (parseContext.treeRoot != NULL);
shannon.woods%transgaming.com@gtempaccount.com0bbed382013-04-13 03:38:07 +0000216
shannon.woods%transgaming.com@gtempaccount.com5524db02013-04-13 03:38:16 +0000217 shaderVersion = parseContext.getShaderVersion();
Zhenyao Modb9b40b2014-10-29 15:00:04 -0700218 if (success && MapSpecToShaderVersion(shaderSpec) < shaderVersion)
219 {
220 infoSink.info.prefix(EPrefixError);
221 infoSink.info << "unsupported shader version";
222 success = false;
223 }
shannon.woods%transgaming.com@gtempaccount.com0bbed382013-04-13 03:38:07 +0000224
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200225 TIntermNode *root = NULL;
226
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800227 if (success)
228 {
Zhenyao Mo94ac7b72014-10-15 18:22:08 -0700229 mPragma = parseContext.pragma();
230 if (mPragma.stdgl.invariantAll)
231 {
232 symbolTable.setGlobalInvariant();
233 }
234
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200235 root = parseContext.treeRoot;
alokp@chromium.orgb59a7782010-11-24 18:38:33 +0000236 success = intermediate.postProcess(root);
237
Jamie Madill6654bc92014-03-26 14:01:57 -0400238 // Disallow expressions deemed too complex.
239 if (success && (compileOptions & SH_LIMIT_EXPRESSION_COMPLEXITY))
240 success = limitExpressionComplexity(root);
241
Corentin Wallez71d147f2015-02-11 11:15:24 -0800242 // Create the function DAG and check there is no recursion
zmo@google.comb1762df2011-07-30 02:04:23 +0000243 if (success)
Corentin Wallez71d147f2015-02-11 11:15:24 -0800244 success = initCallDag(root);
245
246 if (success && (compileOptions & SH_LIMIT_CALL_STACK_DEPTH))
247 success = checkCallDepth();
248
249 // Checks which functions are used and if "main" exists
250 if (success)
251 {
252 functionMetadata.clear();
253 functionMetadata.resize(mCallDag.size());
254 success = tagUsedFunctions();
255 }
zmo@google.comb1762df2011-07-30 02:04:23 +0000256
Corentin Walleza094a8a2015-04-07 11:53:06 -0700257 if (success && !(compileOptions & SH_DONT_PRUNE_UNUSED_FUNCTIONS))
258 success = pruneUnusedFunctions(root);
259
Olli Etuahoc6833112015-04-22 15:15:54 +0300260 // Prune empty declarations to work around driver bugs and to keep declaration output simple.
261 if (success)
262 PruneEmptyDeclarations(root);
263
Jamie Madill183bde52014-07-02 15:31:19 -0400264 if (success && shaderVersion == 300 && shaderType == GL_FRAGMENT_SHADER)
Jamie Madill05a80ce2013-06-20 11:55:49 -0400265 success = validateOutputs(root);
266
alokp@chromium.orgb59a7782010-11-24 18:38:33 +0000267 if (success && (compileOptions & SH_VALIDATE_LOOP_INDEXING))
268 success = validateLimitations(root);
alokp@chromium.org07620a52010-09-23 17:53:56 +0000269
maxvujovic@gmail.com66ebd012012-05-30 22:18:11 +0000270 if (success && (compileOptions & SH_TIMING_RESTRICTIONS))
maxvujovic@gmail.com77222c92012-06-04 21:06:05 +0000271 success = enforceTimingRestrictions(root, (compileOptions & SH_DEPENDENCY_GRAPH) != 0);
maxvujovic@gmail.com66ebd012012-05-30 22:18:11 +0000272
maxvujovic@gmail.com430f5e02012-06-08 17:47:59 +0000273 if (success && shaderSpec == SH_CSS_SHADERS_SPEC)
274 rewriteCSSShader(root);
275
zmo@google.com0c6bb7a2011-08-17 19:39:58 +0000276 // Unroll for-loop markup needs to happen after validateLimitations pass.
277 if (success && (compileOptions & SH_UNROLL_FOR_LOOP_WITH_INTEGER_INDEX))
Zhenyao Mo3cdfcce2014-03-07 13:00:08 -0800278 {
279 ForLoopUnrollMarker marker(ForLoopUnrollMarker::kIntegerIndex);
Zhenyao Mo550c6002014-02-26 15:40:48 -0800280 root->traverse(&marker);
281 }
282 if (success && (compileOptions & SH_UNROLL_FOR_LOOP_WITH_SAMPLER_ARRAY_INDEX))
Zhenyao Mo3cdfcce2014-03-07 13:00:08 -0800283 {
284 ForLoopUnrollMarker marker(ForLoopUnrollMarker::kSamplerArrayIndex);
Zhenyao Mo550c6002014-02-26 15:40:48 -0800285 root->traverse(&marker);
286 if (marker.samplerArrayIndexIsFloatLoopIndex())
287 {
288 infoSink.info.prefix(EPrefixError);
289 infoSink.info << "sampler array index is float loop index";
290 success = false;
291 }
292 }
zmo@google.com0c6bb7a2011-08-17 19:39:58 +0000293
zmo@google.com32e97312011-08-24 01:03:11 +0000294 // Built-in function emulation needs to happen after validateLimitations pass.
Olli Etuaho8efc5ad2015-03-03 17:21:10 +0200295 if (success)
296 {
297 initBuiltInFunctionEmulator(&builtInFunctionEmulator, compileOptions);
zmo@google.com32e97312011-08-24 01:03:11 +0000298 builtInFunctionEmulator.MarkBuiltInFunctionsForEmulation(root);
Olli Etuaho8efc5ad2015-03-03 17:21:10 +0200299 }
zmo@google.com32e97312011-08-24 01:03:11 +0000300
daniel@transgaming.com4167cc92013-01-11 04:11:53 +0000301 // Clamping uniform array bounds needs to happen after validateLimitations pass.
302 if (success && (compileOptions & SH_CLAMP_INDIRECT_ARRAY_BOUNDS))
303 arrayBoundsClamper.MarkIndirectArrayBoundsForClamping(root);
304
Jamie Madill183bde52014-07-02 15:31:19 -0400305 if (success && shaderType == GL_VERTEX_SHADER && (compileOptions & SH_INIT_GL_POSITION))
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800306 initializeGLPosition(root);
Zhenyao Moac44cd22013-09-23 14:57:09 -0400307
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800308 if (success && (compileOptions & SH_UNFOLD_SHORT_CIRCUIT))
309 {
Zhenyao Mo7cab38b2013-10-15 12:59:30 -0700310 UnfoldShortCircuitAST unfoldShortCircuit;
311 root->traverse(&unfoldShortCircuit);
312 unfoldShortCircuit.updateTree();
313 }
314
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800315 if (success && (compileOptions & SH_VARIABLES))
316 {
Zhenyao Mo74da9f22013-09-23 14:57:01 -0400317 collectVariables(root);
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800318 if (compileOptions & SH_ENFORCE_PACKING_RESTRICTIONS)
319 {
gman@chromium.org8d804792012-10-17 21:33:48 +0000320 success = enforcePackingRestrictions();
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800321 if (!success)
322 {
Jamie Madill075edd82013-07-08 13:30:19 -0400323 infoSink.info.prefix(EPrefixError);
324 infoSink.info << "too many uniforms";
gman@chromium.org8d804792012-10-17 21:33:48 +0000325 }
326 }
Jamie Madill183bde52014-07-02 15:31:19 -0400327 if (success && shaderType == GL_VERTEX_SHADER &&
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800328 (compileOptions & SH_INIT_VARYINGS_WITHOUT_STATIC_USE))
329 initializeVaryingsWithoutStaticUse(root);
gman@chromium.org8d804792012-10-17 21:33:48 +0000330 }
zmo@google.comfd747b82011-04-23 01:30:07 +0000331
Zhenyao Mocd68fe72014-07-11 10:45:44 -0700332 if (success && (compileOptions & SH_SCALARIZE_VEC_AND_MAT_CONSTRUCTOR_ARGS))
333 {
Zhenyao Modaf56572014-08-06 16:18:30 -0700334 ScalarizeVecAndMatConstructorArgs scalarizer(
335 shaderType, fragmentPrecisionHigh);
Zhenyao Mocd68fe72014-07-11 10:45:44 -0700336 root->traverse(&scalarizer);
337 }
338
Zhenyao Moe740add2014-07-18 17:01:01 -0700339 if (success && (compileOptions & SH_REGENERATE_STRUCT_NAMES))
340 {
341 RegenerateStructNames gen(symbolTable, shaderVersion);
342 root->traverse(&gen);
343 }
alokp@chromium.org07620a52010-09-23 17:53:56 +0000344 }
345
Zhenyao Mo7faf1a12014-04-25 18:03:56 -0700346 SetGlobalParseContext(NULL);
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200347 if (success)
348 return root;
349
350 return NULL;
351}
352
353bool TCompiler::compile(const char* const shaderStrings[],
354 size_t numStrings, int compileOptions)
355{
356 if (numStrings == 0)
357 return true;
358
359 TScopedPoolAllocator scopedAlloc(&allocator);
360 TIntermNode *root = compileTreeImpl(shaderStrings, numStrings, compileOptions);
361
362 if (root)
363 {
364 if (compileOptions & SH_INTERMEDIATE_TREE)
365 TIntermediate::outputTree(root, infoSink.info);
366
367 if (compileOptions & SH_OBJECT_CODE)
368 translate(root, compileOptions);
369
370 // The IntermNode tree doesn't need to be deleted here, since the
371 // memory will be freed in a big chunk by the PoolAllocator.
372 return true;
373 }
374 return false;
alokp@chromium.org07620a52010-09-23 17:53:56 +0000375}
376
Nicolas Capens49a88872013-06-20 09:54:03 -0400377bool TCompiler::InitBuiltInSymbolTable(const ShBuiltInResources &resources)
alokp@chromium.org07620a52010-09-23 17:53:56 +0000378{
shannon.woods%transgaming.com@gtempaccount.com18b4c4b2013-04-13 03:31:40 +0000379 compileResources = resources;
Shannon Woods2d76e5f2014-05-16 17:46:41 -0400380 setResourceString();
shannonwoods@chromium.org2ac0be92013-05-30 00:02:27 +0000381
Nicolas Capens49a88872013-06-20 09:54:03 -0400382 assert(symbolTable.isEmpty());
383 symbolTable.push(); // COMMON_BUILTINS
384 symbolTable.push(); // ESSL1_BUILTINS
385 symbolTable.push(); // ESSL3_BUILTINS
shannonwoods@chromium.org2ac0be92013-05-30 00:02:27 +0000386
Nicolas Capens49a88872013-06-20 09:54:03 -0400387 TPublicType integer;
388 integer.type = EbtInt;
389 integer.primarySize = 1;
390 integer.secondarySize = 1;
391 integer.array = false;
392
393 TPublicType floatingPoint;
394 floatingPoint.type = EbtFloat;
395 floatingPoint.primarySize = 1;
396 floatingPoint.secondarySize = 1;
397 floatingPoint.array = false;
398
Zhenyao Moa5a1dfc2013-09-23 14:57:03 -0400399 TPublicType sampler;
400 sampler.primarySize = 1;
401 sampler.secondarySize = 1;
402 sampler.array = false;
403
Nicolas Capens49a88872013-06-20 09:54:03 -0400404 switch(shaderType)
405 {
Jamie Madill183bde52014-07-02 15:31:19 -0400406 case GL_FRAGMENT_SHADER:
Nicolas Capens49a88872013-06-20 09:54:03 -0400407 symbolTable.setDefaultPrecision(integer, EbpMedium);
408 break;
Jamie Madill183bde52014-07-02 15:31:19 -0400409 case GL_VERTEX_SHADER:
Nicolas Capens49a88872013-06-20 09:54:03 -0400410 symbolTable.setDefaultPrecision(integer, EbpHigh);
411 symbolTable.setDefaultPrecision(floatingPoint, EbpHigh);
412 break;
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800413 default:
414 assert(false && "Language not supported");
Nicolas Capens49a88872013-06-20 09:54:03 -0400415 }
Zhenyao Moa5a1dfc2013-09-23 14:57:03 -0400416 // We set defaults for all the sampler types, even those that are
417 // only available if an extension exists.
418 for (int samplerType = EbtGuardSamplerBegin + 1;
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800419 samplerType < EbtGuardSamplerEnd; ++samplerType)
420 {
Zhenyao Moa5a1dfc2013-09-23 14:57:03 -0400421 sampler.type = static_cast<TBasicType>(samplerType);
422 symbolTable.setDefaultPrecision(sampler, EbpLow);
423 }
Nicolas Capens49a88872013-06-20 09:54:03 -0400424
Jamie Madill1b452142013-07-12 14:51:11 -0400425 InsertBuiltInFunctions(shaderType, shaderSpec, resources, symbolTable);
Nicolas Capens49a88872013-06-20 09:54:03 -0400426
427 IdentifyBuiltIns(shaderType, shaderSpec, resources, symbolTable);
428
429 return true;
alokp@chromium.org07620a52010-09-23 17:53:56 +0000430}
431
Shannon Woods2d76e5f2014-05-16 17:46:41 -0400432void TCompiler::setResourceString()
433{
434 std::ostringstream strstream;
435 strstream << ":MaxVertexAttribs:" << compileResources.MaxVertexAttribs
436 << ":MaxVertexUniformVectors:" << compileResources.MaxVertexUniformVectors
437 << ":MaxVaryingVectors:" << compileResources.MaxVaryingVectors
438 << ":MaxVertexTextureImageUnits:" << compileResources.MaxVertexTextureImageUnits
439 << ":MaxCombinedTextureImageUnits:" << compileResources.MaxCombinedTextureImageUnits
440 << ":MaxTextureImageUnits:" << compileResources.MaxTextureImageUnits
441 << ":MaxFragmentUniformVectors:" << compileResources.MaxFragmentUniformVectors
442 << ":MaxDrawBuffers:" << compileResources.MaxDrawBuffers
443 << ":OES_standard_derivatives:" << compileResources.OES_standard_derivatives
444 << ":OES_EGL_image_external:" << compileResources.OES_EGL_image_external
445 << ":ARB_texture_rectangle:" << compileResources.ARB_texture_rectangle
446 << ":EXT_draw_buffers:" << compileResources.EXT_draw_buffers
447 << ":FragmentPrecisionHigh:" << compileResources.FragmentPrecisionHigh
448 << ":MaxExpressionComplexity:" << compileResources.MaxExpressionComplexity
449 << ":MaxCallStackDepth:" << compileResources.MaxCallStackDepth
450 << ":EXT_frag_depth:" << compileResources.EXT_frag_depth
451 << ":EXT_shader_texture_lod:" << compileResources.EXT_shader_texture_lod
Erik Dahlströmea7a2122014-11-17 16:15:57 +0100452 << ":EXT_shader_framebuffer_fetch:" << compileResources.EXT_shader_framebuffer_fetch
453 << ":NV_shader_framebuffer_fetch:" << compileResources.NV_shader_framebuffer_fetch
454 << ":ARM_shader_framebuffer_fetch:" << compileResources.ARM_shader_framebuffer_fetch
Shannon Woods2d76e5f2014-05-16 17:46:41 -0400455 << ":MaxVertexOutputVectors:" << compileResources.MaxVertexOutputVectors
456 << ":MaxFragmentInputVectors:" << compileResources.MaxFragmentInputVectors
457 << ":MinProgramTexelOffset:" << compileResources.MinProgramTexelOffset
Olli Etuahoe61209a2014-09-26 12:01:17 +0300458 << ":MaxProgramTexelOffset:" << compileResources.MaxProgramTexelOffset
Olli Etuaho853dc1a2014-11-06 17:25:48 +0200459 << ":NV_draw_buffers:" << compileResources.NV_draw_buffers
460 << ":WEBGL_debug_shader_precision:" << compileResources.WEBGL_debug_shader_precision;
Shannon Woods2d76e5f2014-05-16 17:46:41 -0400461
462 builtInResourcesString = strstream.str();
463}
464
alokp@chromium.org07620a52010-09-23 17:53:56 +0000465void TCompiler::clearResults()
466{
daniel@transgaming.com4167cc92013-01-11 04:11:53 +0000467 arrayBoundsClamper.Cleanup();
alokp@chromium.org07620a52010-09-23 17:53:56 +0000468 infoSink.info.erase();
469 infoSink.obj.erase();
470 infoSink.debug.erase();
471
Jamie Madilled27c722014-07-02 15:31:23 -0400472 attributes.clear();
473 outputVariables.clear();
alokp@chromium.org07620a52010-09-23 17:53:56 +0000474 uniforms.clear();
Jamie Madill23a8a432014-07-09 13:27:42 -0400475 expandedUniforms.clear();
Zhenyao Mod2d340b2013-09-23 14:57:05 -0400476 varyings.clear();
Jamie Madilled27c722014-07-02 15:31:23 -0400477 interfaceBlocks.clear();
zmo@google.coma3b4ab42011-09-16 00:53:26 +0000478
479 builtInFunctionEmulator.Cleanup();
daniel@transgaming.com0aa3b5a2012-11-28 19:43:24 +0000480
481 nameMap.clear();
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200482
483 mSourcePath = NULL;
alokp@chromium.org07620a52010-09-23 17:53:56 +0000484}
485
Corentin Wallez71d147f2015-02-11 11:15:24 -0800486bool TCompiler::initCallDag(TIntermNode *root)
zmo@google.comb1762df2011-07-30 02:04:23 +0000487{
Corentin Wallez71d147f2015-02-11 11:15:24 -0800488 mCallDag.clear();
489
490 switch (mCallDag.init(root, &infoSink.info))
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800491 {
Corentin Wallez71d147f2015-02-11 11:15:24 -0800492 case CallDAG::INITDAG_SUCCESS:
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800493 return true;
Corentin Wallez71d147f2015-02-11 11:15:24 -0800494 case CallDAG::INITDAG_RECURSION:
495 infoSink.info.prefix(EPrefixError);
496 infoSink.info << "Function recursion detected";
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800497 return false;
Corentin Wallez71d147f2015-02-11 11:15:24 -0800498 case CallDAG::INITDAG_UNDEFINED:
499 infoSink.info.prefix(EPrefixError);
500 infoSink.info << "Unimplemented function detected";
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800501 return false;
Corentin Wallez71d147f2015-02-11 11:15:24 -0800502 }
503
504 UNREACHABLE();
505 return true;
506}
507
508bool TCompiler::checkCallDepth()
509{
510 std::vector<int> depths(mCallDag.size());
511
512 for (size_t i = 0; i < mCallDag.size(); i++)
513 {
514 int depth = 0;
515 auto &record = mCallDag.getRecordFromIndex(i);
516
517 for (auto &calleeIndex : record.callees)
518 {
519 depth = std::max(depth, depths[calleeIndex] + 1);
520 }
521
522 depths[i] = depth;
523
524 if (depth >= maxCallStackDepth)
525 {
526 // Trace back the function chain to have a meaningful info log.
527 infoSink.info.prefix(EPrefixError);
528 infoSink.info << "Call stack too deep (larger than " << maxCallStackDepth
529 << ") with the following call chain: " << record.name;
530
531 int currentFunction = i;
532 int currentDepth = depth;
533
534 while (currentFunction != -1)
535 {
536 infoSink.info << " -> " << mCallDag.getRecordFromIndex(currentFunction).name;
537
538 int nextFunction = -1;
539 for (auto& calleeIndex : mCallDag.getRecordFromIndex(currentFunction).callees)
540 {
541 if (depths[calleeIndex] == currentDepth - 1)
542 {
543 currentDepth--;
544 nextFunction = calleeIndex;
545 }
546 }
547
548 currentFunction = nextFunction;
549 }
550
551 return false;
552 }
553 }
554
555 return true;
556}
557
558bool TCompiler::tagUsedFunctions()
559{
560 // Search from main, starting from the end of the DAG as it usually is the root.
561 for (int i = mCallDag.size(); i-- > 0;)
562 {
563 if (mCallDag.getRecordFromIndex(i).name == "main(")
564 {
565 internalTagUsedFunction(i);
566 return true;
567 }
568 }
569
570 infoSink.info.prefix(EPrefixError);
571 infoSink.info << "Missing main()";
572 return false;
573}
574
575void TCompiler::internalTagUsedFunction(size_t index)
576{
577 if (functionMetadata[index].used)
578 {
579 return;
580 }
581
582 functionMetadata[index].used = true;
583
584 for (int calleeIndex : mCallDag.getRecordFromIndex(index).callees)
585 {
586 internalTagUsedFunction(calleeIndex);
zmo@google.comb1762df2011-07-30 02:04:23 +0000587 }
588}
589
Corentin Walleza094a8a2015-04-07 11:53:06 -0700590// A predicate for the stl that returns if a top-level node is unused
591class TCompiler::UnusedPredicate
592{
593 public:
594 UnusedPredicate(const CallDAG *callDag, const std::vector<FunctionMetadata> *metadatas)
595 : mCallDag(callDag),
596 mMetadatas(metadatas)
597 {
598 }
599
600 bool operator ()(TIntermNode *node)
601 {
602 const TIntermAggregate *asAggregate = node->getAsAggregate();
603
604 if (asAggregate == nullptr)
605 {
606 return false;
607 }
608
609 if (!(asAggregate->getOp() == EOpFunction || asAggregate->getOp() == EOpPrototype))
610 {
611 return false;
612 }
613
614 size_t callDagIndex = mCallDag->findIndex(asAggregate);
615 if (callDagIndex == CallDAG::InvalidIndex)
616 {
617 // This happens only for unimplemented prototypes which are thus unused
618 ASSERT(asAggregate->getOp() == EOpPrototype);
619 return true;
620 }
621
622 ASSERT(callDagIndex < mMetadatas->size());
623 return !(*mMetadatas)[callDagIndex].used;
624 }
625
626 private:
627 const CallDAG *mCallDag;
628 const std::vector<FunctionMetadata> *mMetadatas;
629};
630
631bool TCompiler::pruneUnusedFunctions(TIntermNode *root)
632{
633 TIntermAggregate *rootNode = root->getAsAggregate();
634 ASSERT(rootNode != nullptr);
635
636 UnusedPredicate isUnused(&mCallDag, &functionMetadata);
637 TIntermSequence *sequence = rootNode->getSequence();
638 sequence->erase(std::remove_if(sequence->begin(), sequence->end(), isUnused), sequence->end());
639
640 return true;
641}
642
Jamie Madill05a80ce2013-06-20 11:55:49 -0400643bool TCompiler::validateOutputs(TIntermNode* root)
644{
645 ValidateOutputs validateOutputs(infoSink.info, compileResources.MaxDrawBuffers);
646 root->traverse(&validateOutputs);
647 return (validateOutputs.numErrors() == 0);
648}
649
maxvujovic@gmail.com430f5e02012-06-08 17:47:59 +0000650void TCompiler::rewriteCSSShader(TIntermNode* root)
651{
652 RenameFunction renamer("main(", "css_main(");
653 root->traverse(&renamer);
654}
655
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800656bool TCompiler::validateLimitations(TIntermNode* root)
657{
alokp@chromium.orgb59a7782010-11-24 18:38:33 +0000658 ValidateLimitations validate(shaderType, infoSink.info);
659 root->traverse(&validate);
660 return validate.numErrors() == 0;
661}
662
maxvujovic@gmail.com77222c92012-06-04 21:06:05 +0000663bool TCompiler::enforceTimingRestrictions(TIntermNode* root, bool outputGraph)
maxvujovic@gmail.com66ebd012012-05-30 22:18:11 +0000664{
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800665 if (shaderSpec != SH_WEBGL_SPEC)
666 {
maxvujovic@gmail.com66ebd012012-05-30 22:18:11 +0000667 infoSink.info << "Timing restrictions must be enforced under the WebGL spec.";
668 return false;
669 }
670
Jamie Madill183bde52014-07-02 15:31:19 -0400671 if (shaderType == GL_FRAGMENT_SHADER)
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800672 {
maxvujovic@gmail.com66ebd012012-05-30 22:18:11 +0000673 TDependencyGraph graph(root);
674
675 // Output any errors first.
maxvujovic@gmail.com77222c92012-06-04 21:06:05 +0000676 bool success = enforceFragmentShaderTimingRestrictions(graph);
Jamie Madill5508f392014-02-20 13:31:36 -0500677
maxvujovic@gmail.com66ebd012012-05-30 22:18:11 +0000678 // Then, output the dependency graph.
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800679 if (outputGraph)
680 {
maxvujovic@gmail.com66ebd012012-05-30 22:18:11 +0000681 TDependencyGraphOutput output(infoSink.info);
682 output.outputAllSpanningTrees(graph);
683 }
Jamie Madill5508f392014-02-20 13:31:36 -0500684
maxvujovic@gmail.com66ebd012012-05-30 22:18:11 +0000685 return success;
686 }
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800687 else
688 {
maxvujovic@gmail.com77222c92012-06-04 21:06:05 +0000689 return enforceVertexShaderTimingRestrictions(root);
maxvujovic@gmail.com66ebd012012-05-30 22:18:11 +0000690 }
691}
692
Jamie Madilleb1a0102013-07-08 13:31:38 -0400693bool TCompiler::limitExpressionComplexity(TIntermNode* root)
694{
Jamie Madill6654bc92014-03-26 14:01:57 -0400695 TMaxDepthTraverser traverser(maxExpressionComplexity+1);
Jamie Madilleb1a0102013-07-08 13:31:38 -0400696 root->traverse(&traverser);
Jamie Madill6654bc92014-03-26 14:01:57 -0400697
698 if (traverser.getMaxDepth() > maxExpressionComplexity)
699 {
700 infoSink.info << "Expression too complex.";
701 return false;
702 }
703
Jamie Madilleb1a0102013-07-08 13:31:38 -0400704 TDependencyGraph graph(root);
705
706 for (TFunctionCallVector::const_iterator iter = graph.beginUserDefinedFunctionCalls();
707 iter != graph.endUserDefinedFunctionCalls();
708 ++iter)
709 {
710 TGraphFunctionCall* samplerSymbol = *iter;
711 TDependencyGraphTraverser graphTraverser;
712 samplerSymbol->traverse(&graphTraverser);
713 }
714
Jamie Madilleb1a0102013-07-08 13:31:38 -0400715 return true;
716}
717
maxvujovic@gmail.com77222c92012-06-04 21:06:05 +0000718bool TCompiler::enforceFragmentShaderTimingRestrictions(const TDependencyGraph& graph)
maxvujovic@gmail.com66ebd012012-05-30 22:18:11 +0000719{
maxvujovic@gmail.com77222c92012-06-04 21:06:05 +0000720 RestrictFragmentShaderTiming restrictor(infoSink.info);
maxvujovic@gmail.com66ebd012012-05-30 22:18:11 +0000721 restrictor.enforceRestrictions(graph);
722 return restrictor.numErrors() == 0;
723}
724
maxvujovic@gmail.com77222c92012-06-04 21:06:05 +0000725bool TCompiler::enforceVertexShaderTimingRestrictions(TIntermNode* root)
maxvujovic@gmail.com66ebd012012-05-30 22:18:11 +0000726{
maxvujovic@gmail.com77222c92012-06-04 21:06:05 +0000727 RestrictVertexShaderTiming restrictor(infoSink.info);
maxvujovic@gmail.com66ebd012012-05-30 22:18:11 +0000728 restrictor.enforceRestrictions(root);
729 return restrictor.numErrors() == 0;
730}
731
Zhenyao Mo74da9f22013-09-23 14:57:01 -0400732void TCompiler::collectVariables(TIntermNode* root)
alokp@chromium.org07620a52010-09-23 17:53:56 +0000733{
Jamie Madilla2fbb842014-09-03 09:40:47 -0400734 sh::CollectVariables collect(&attributes,
735 &outputVariables,
736 &uniforms,
737 &varyings,
738 &interfaceBlocks,
Zhenyao Mo94ac7b72014-10-15 18:22:08 -0700739 hashFunction,
740 symbolTable);
alokp@chromium.org07620a52010-09-23 17:53:56 +0000741 root->traverse(&collect);
Jamie Madill23a8a432014-07-09 13:27:42 -0400742
Zhenyao Mo409078f2014-10-28 13:23:18 -0700743 // This is for enforcePackingRestriction().
744 sh::ExpandUniforms(uniforms, &expandedUniforms);
alokp@chromium.org07620a52010-09-23 17:53:56 +0000745}
zmo@google.comfd747b82011-04-23 01:30:07 +0000746
gman@chromium.org8d804792012-10-17 21:33:48 +0000747bool TCompiler::enforcePackingRestrictions()
748{
749 VariablePacker packer;
Jamie Madill23a8a432014-07-09 13:27:42 -0400750 return packer.CheckVariablesWithinPackingLimits(maxUniformVectors, expandedUniforms);
gman@chromium.org8d804792012-10-17 21:33:48 +0000751}
752
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800753void TCompiler::initializeGLPosition(TIntermNode* root)
754{
755 InitializeVariables::InitVariableInfoList variables;
756 InitializeVariables::InitVariableInfo var(
757 "gl_Position", TType(EbtFloat, EbpUndefined, EvqPosition, 4));
758 variables.push_back(var);
759 InitializeVariables initializer(variables);
760 root->traverse(&initializer);
761}
762
763void TCompiler::initializeVaryingsWithoutStaticUse(TIntermNode* root)
764{
765 InitializeVariables::InitVariableInfoList variables;
766 for (size_t ii = 0; ii < varyings.size(); ++ii)
767 {
Jamie Madilla718c1e2014-07-02 15:31:22 -0400768 const sh::Varying& varying = varyings[ii];
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800769 if (varying.staticUse)
770 continue;
Jamie Madillaa72d782014-07-02 15:31:19 -0400771 unsigned char primarySize = static_cast<unsigned char>(gl::VariableColumnCount(varying.type));
772 unsigned char secondarySize = static_cast<unsigned char>(gl::VariableRowCount(varying.type));
Jamie Madilla718c1e2014-07-02 15:31:22 -0400773 TType type(EbtFloat, EbpUndefined, EvqVaryingOut, primarySize, secondarySize, varying.isArray());
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800774 TString name = varying.name.c_str();
Jamie Madilla718c1e2014-07-02 15:31:22 -0400775 if (varying.isArray())
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800776 {
Jamie Madilla718c1e2014-07-02 15:31:22 -0400777 type.setArraySize(varying.arraySize);
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800778 name = name.substr(0, name.find_first_of('['));
779 }
780
781 InitializeVariables::InitVariableInfo var(name, type);
782 variables.push_back(var);
783 }
784 InitializeVariables initializer(variables);
785 root->traverse(&initializer);
786}
787
zmo@google.com5601ea02011-06-10 18:23:25 +0000788const TExtensionBehavior& TCompiler::getExtensionBehavior() const
789{
790 return extensionBehavior;
791}
zmo@google.com32e97312011-08-24 01:03:11 +0000792
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200793const char *TCompiler::getSourcePath() const
794{
795 return mSourcePath;
796}
797
shannon.woods%transgaming.com@gtempaccount.com18b4c4b2013-04-13 03:31:40 +0000798const ShBuiltInResources& TCompiler::getResources() const
799{
800 return compileResources;
801}
802
daniel@transgaming.com4167cc92013-01-11 04:11:53 +0000803const ArrayBoundsClamper& TCompiler::getArrayBoundsClamper() const
804{
805 return arrayBoundsClamper;
806}
807
shannon.woods@transgaming.com1d432bb2013-01-25 21:57:28 +0000808ShArrayIndexClampingStrategy TCompiler::getArrayIndexClampingStrategy() const
809{
810 return clampingStrategy;
811}
812
Olli Etuaho8efc5ad2015-03-03 17:21:10 +0200813const BuiltInFunctionEmulator& TCompiler::getBuiltInFunctionEmulator() const
shannon.woods@transgaming.com1d432bb2013-01-25 21:57:28 +0000814{
815 return builtInFunctionEmulator;
816}
Zhenyao Mo94ac7b72014-10-15 18:22:08 -0700817
818void TCompiler::writePragma()
819{
820 TInfoSinkBase &sink = infoSink.obj;
821 if (mPragma.stdgl.invariantAll)
822 sink << "#pragma STDGL invariant(all)\n";
823}