blob: 6bd8f74684a6830aaa23fe3f130e14cebc58e8b8 [file] [log] [blame]
ethannicholasb3058bd2016-07-01 08:22:01 -07001/*
2 * Copyright 2016 Google Inc.
3 *
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
6 */
Mike Klein6ad99092016-10-26 10:35:22 -04007
Mike Kleinc0bd9f92019-04-23 12:05:21 -05008#include "src/sksl/SkSLCompiler.h"
ethannicholasb3058bd2016-07-01 08:22:01 -07009
John Stilesfbd050b2020-08-03 13:21:46 -040010#include <memory>
John Stilesb8e010c2020-08-11 18:05:39 -040011#include <unordered_set>
John Stilesfbd050b2020-08-03 13:21:46 -040012
John Stilesb92641c2020-08-31 18:09:01 -040013#include "src/sksl/SkSLAnalysis.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050014#include "src/sksl/SkSLByteCodeGenerator.h"
15#include "src/sksl/SkSLCFGGenerator.h"
16#include "src/sksl/SkSLCPPCodeGenerator.h"
17#include "src/sksl/SkSLGLSLCodeGenerator.h"
18#include "src/sksl/SkSLHCodeGenerator.h"
19#include "src/sksl/SkSLIRGenerator.h"
20#include "src/sksl/SkSLMetalCodeGenerator.h"
21#include "src/sksl/SkSLPipelineStageCodeGenerator.h"
Ethan Nicholasc18bb512020-07-28 14:46:53 -040022#include "src/sksl/SkSLRehydrator.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050023#include "src/sksl/SkSLSPIRVCodeGenerator.h"
Brian Osmanc0243912020-02-19 15:35:26 -050024#include "src/sksl/SkSLSPIRVtoHLSL.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050025#include "src/sksl/ir/SkSLEnum.h"
26#include "src/sksl/ir/SkSLExpression.h"
27#include "src/sksl/ir/SkSLExpressionStatement.h"
28#include "src/sksl/ir/SkSLFunctionCall.h"
29#include "src/sksl/ir/SkSLIntLiteral.h"
30#include "src/sksl/ir/SkSLModifiersDeclaration.h"
31#include "src/sksl/ir/SkSLNop.h"
32#include "src/sksl/ir/SkSLSymbolTable.h"
33#include "src/sksl/ir/SkSLTernaryExpression.h"
34#include "src/sksl/ir/SkSLUnresolvedFunction.h"
35#include "src/sksl/ir/SkSLVarDeclarations.h"
ethannicholasb3058bd2016-07-01 08:22:01 -070036
Ethan Nicholasb33fa3f2020-08-06 13:00:19 -040037#include <fstream>
38
Ethan Nicholasa11035b2019-11-26 16:27:47 -050039#if !defined(SKSL_STANDALONE) & SK_SUPPORT_GPU
40#include "include/gpu/GrContextOptions.h"
41#include "src/gpu/GrShaderCaps.h"
42#endif
43
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -040044#ifdef SK_ENABLE_SPIRV_VALIDATION
45#include "spirv-tools/libspirv.hpp"
46#endif
47
Brian Osmandd496172020-08-08 08:17:18 -040048#if !SKSL_STANDALONE
Ethan Nicholasc18bb512020-07-28 14:46:53 -040049
50#include "src/sksl/generated/sksl_fp.dehydrated.sksl"
51#include "src/sksl/generated/sksl_frag.dehydrated.sksl"
52#include "src/sksl/generated/sksl_geom.dehydrated.sksl"
53#include "src/sksl/generated/sksl_gpu.dehydrated.sksl"
54#include "src/sksl/generated/sksl_interp.dehydrated.sksl"
55#include "src/sksl/generated/sksl_pipeline.dehydrated.sksl"
56#include "src/sksl/generated/sksl_vert.dehydrated.sksl"
57
58#else
59
Brian Osmandd496172020-08-08 08:17:18 -040060// GN generates or copies all of these files to the skslc executable directory
61static const char SKSL_GPU_INCLUDE[] = "sksl_gpu.sksl";
62static const char SKSL_INTERP_INCLUDE[] = "sksl_interp.sksl";
63static const char SKSL_VERT_INCLUDE[] = "sksl_vert.sksl";
64static const char SKSL_FRAG_INCLUDE[] = "sksl_frag.sksl";
65static const char SKSL_GEOM_INCLUDE[] = "sksl_geom.sksl";
66static const char SKSL_FP_INCLUDE[] = "sksl_fp.sksl";
67static const char SKSL_PIPELINE_INCLUDE[] = "sksl_pipeline.sksl";
Ethan Nicholasc18bb512020-07-28 14:46:53 -040068
69#endif
Ethan Nicholas0d997662019-04-08 09:46:01 -040070
ethannicholasb3058bd2016-07-01 08:22:01 -070071namespace SkSL {
72
Ethan Nicholasdb80f692019-11-22 14:06:12 -050073static void grab_intrinsics(std::vector<std::unique_ptr<ProgramElement>>* src,
John Stiles810c8cf2020-08-26 19:46:27 -040074 IRIntrinsicMap* target) {
Brian Osman08f986d2020-05-13 17:06:46 -040075 for (auto iter = src->begin(); iter != src->end(); ) {
76 std::unique_ptr<ProgramElement>& element = *iter;
Ethan Nicholase6592142020-09-08 10:22:09 -040077 switch (element->kind()) {
78 case ProgramElement::Kind::kFunction: {
John Stiles3dc0da62020-08-19 17:48:31 -040079 FunctionDefinition& f = element->as<FunctionDefinition>();
Brian Osman08f986d2020-05-13 17:06:46 -040080 SkASSERT(f.fDeclaration.fBuiltin);
Ethan Nicholasc18bb512020-07-28 14:46:53 -040081 String key = f.fDeclaration.description();
Brian Osman08f986d2020-05-13 17:06:46 -040082 SkASSERT(target->find(key) == target->end());
John Stiles810c8cf2020-08-26 19:46:27 -040083 (*target)[key] = IRIntrinsic{std::move(element), /*fAlreadyIncluded=*/false};
Brian Osman08f986d2020-05-13 17:06:46 -040084 iter = src->erase(iter);
Ethan Nicholasdb80f692019-11-22 14:06:12 -050085 break;
86 }
Ethan Nicholase6592142020-09-08 10:22:09 -040087 case ProgramElement::Kind::kEnum: {
John Stiles3dc0da62020-08-19 17:48:31 -040088 Enum& e = element->as<Enum>();
Ethan Nicholasdb80f692019-11-22 14:06:12 -050089 StringFragment name = e.fTypeName;
90 SkASSERT(target->find(name) == target->end());
John Stiles810c8cf2020-08-26 19:46:27 -040091 (*target)[name] = IRIntrinsic{std::move(element), /*fAlreadyIncluded=*/false};
Brian Osman08f986d2020-05-13 17:06:46 -040092 iter = src->erase(iter);
Ethan Nicholasdb80f692019-11-22 14:06:12 -050093 break;
94 }
95 default:
96 printf("unsupported include file element\n");
97 SkASSERT(false);
98 }
99 }
100}
101
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -0400102Compiler::Compiler(Flags flags)
John Stiles810c8cf2020-08-26 19:46:27 -0400103: fGPUIntrinsics(std::make_unique<IRIntrinsicMap>())
104, fInterpreterIntrinsics(std::make_unique<IRIntrinsicMap>())
105, fFlags(flags)
106, fContext(std::make_shared<Context>())
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -0400107, fErrorCount(0) {
John Stiles656427a2020-08-27 15:26:26 -0400108 auto symbols = std::make_shared<SymbolTable>(this);
John Stiles7b463002020-08-31 17:29:21 -0400109 fIRGenerator = std::make_unique<IRGenerator>(fContext.get(), &fInliner, symbols, *this);
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400110 #define ADD_TYPE(t) symbols->addWithoutOwnership(fContext->f ## t ## _Type->fName, \
111 fContext->f ## t ## _Type.get())
ethannicholasb3058bd2016-07-01 08:22:01 -0700112 ADD_TYPE(Void);
113 ADD_TYPE(Float);
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400114 ADD_TYPE(Float2);
115 ADD_TYPE(Float3);
116 ADD_TYPE(Float4);
Ethan Nicholasdcba08e2017-08-02 10:52:54 -0400117 ADD_TYPE(Half);
118 ADD_TYPE(Half2);
119 ADD_TYPE(Half3);
120 ADD_TYPE(Half4);
ethannicholasb3058bd2016-07-01 08:22:01 -0700121 ADD_TYPE(Int);
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400122 ADD_TYPE(Int2);
123 ADD_TYPE(Int3);
124 ADD_TYPE(Int4);
ethannicholasb3058bd2016-07-01 08:22:01 -0700125 ADD_TYPE(UInt);
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400126 ADD_TYPE(UInt2);
127 ADD_TYPE(UInt3);
128 ADD_TYPE(UInt4);
Ethan Nicholasdcba08e2017-08-02 10:52:54 -0400129 ADD_TYPE(Short);
130 ADD_TYPE(Short2);
131 ADD_TYPE(Short3);
132 ADD_TYPE(Short4);
133 ADD_TYPE(UShort);
134 ADD_TYPE(UShort2);
135 ADD_TYPE(UShort3);
136 ADD_TYPE(UShort4);
Ruiqi Maob609e6d2018-07-17 10:19:38 -0400137 ADD_TYPE(Byte);
138 ADD_TYPE(Byte2);
139 ADD_TYPE(Byte3);
140 ADD_TYPE(Byte4);
141 ADD_TYPE(UByte);
142 ADD_TYPE(UByte2);
143 ADD_TYPE(UByte3);
144 ADD_TYPE(UByte4);
ethannicholasb3058bd2016-07-01 08:22:01 -0700145 ADD_TYPE(Bool);
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400146 ADD_TYPE(Bool2);
147 ADD_TYPE(Bool3);
148 ADD_TYPE(Bool4);
149 ADD_TYPE(Float2x2);
150 ADD_TYPE(Float2x3);
151 ADD_TYPE(Float2x4);
152 ADD_TYPE(Float3x2);
153 ADD_TYPE(Float3x3);
154 ADD_TYPE(Float3x4);
155 ADD_TYPE(Float4x2);
156 ADD_TYPE(Float4x3);
157 ADD_TYPE(Float4x4);
Ethan Nicholasdcba08e2017-08-02 10:52:54 -0400158 ADD_TYPE(Half2x2);
159 ADD_TYPE(Half2x3);
160 ADD_TYPE(Half2x4);
161 ADD_TYPE(Half3x2);
162 ADD_TYPE(Half3x3);
163 ADD_TYPE(Half3x4);
164 ADD_TYPE(Half4x2);
165 ADD_TYPE(Half4x3);
166 ADD_TYPE(Half4x4);
ethannicholasb3058bd2016-07-01 08:22:01 -0700167 ADD_TYPE(GenType);
Ethan Nicholasdcba08e2017-08-02 10:52:54 -0400168 ADD_TYPE(GenHType);
ethannicholasb3058bd2016-07-01 08:22:01 -0700169 ADD_TYPE(GenIType);
170 ADD_TYPE(GenUType);
171 ADD_TYPE(GenBType);
172 ADD_TYPE(Mat);
173 ADD_TYPE(Vec);
174 ADD_TYPE(GVec);
175 ADD_TYPE(GVec2);
176 ADD_TYPE(GVec3);
177 ADD_TYPE(GVec4);
Ethan Nicholasdcba08e2017-08-02 10:52:54 -0400178 ADD_TYPE(HVec);
ethannicholasb3058bd2016-07-01 08:22:01 -0700179 ADD_TYPE(IVec);
180 ADD_TYPE(UVec);
Ethan Nicholasdcba08e2017-08-02 10:52:54 -0400181 ADD_TYPE(SVec);
182 ADD_TYPE(USVec);
Ruiqi Maob609e6d2018-07-17 10:19:38 -0400183 ADD_TYPE(ByteVec);
184 ADD_TYPE(UByteVec);
ethannicholasb3058bd2016-07-01 08:22:01 -0700185 ADD_TYPE(BVec);
186
187 ADD_TYPE(Sampler1D);
188 ADD_TYPE(Sampler2D);
189 ADD_TYPE(Sampler3D);
ethannicholas5961bc92016-10-12 06:39:56 -0700190 ADD_TYPE(SamplerExternalOES);
ethannicholasb3058bd2016-07-01 08:22:01 -0700191 ADD_TYPE(SamplerCube);
192 ADD_TYPE(Sampler2DRect);
193 ADD_TYPE(Sampler1DArray);
194 ADD_TYPE(Sampler2DArray);
195 ADD_TYPE(SamplerCubeArray);
196 ADD_TYPE(SamplerBuffer);
197 ADD_TYPE(Sampler2DMS);
198 ADD_TYPE(Sampler2DMSArray);
199
Brian Salomonbf7b6202016-11-11 16:08:03 -0500200 ADD_TYPE(ISampler2D);
201
Brian Salomon2a51de82016-11-16 12:06:01 -0500202 ADD_TYPE(Image2D);
203 ADD_TYPE(IImage2D);
204
Greg Daniel64773e62016-11-22 09:44:03 -0500205 ADD_TYPE(SubpassInput);
206 ADD_TYPE(SubpassInputMS);
207
ethannicholasb3058bd2016-07-01 08:22:01 -0700208 ADD_TYPE(GSampler1D);
209 ADD_TYPE(GSampler2D);
210 ADD_TYPE(GSampler3D);
211 ADD_TYPE(GSamplerCube);
212 ADD_TYPE(GSampler2DRect);
213 ADD_TYPE(GSampler1DArray);
214 ADD_TYPE(GSampler2DArray);
215 ADD_TYPE(GSamplerCubeArray);
216 ADD_TYPE(GSamplerBuffer);
217 ADD_TYPE(GSampler2DMS);
218 ADD_TYPE(GSampler2DMSArray);
219
220 ADD_TYPE(Sampler1DShadow);
221 ADD_TYPE(Sampler2DShadow);
222 ADD_TYPE(SamplerCubeShadow);
223 ADD_TYPE(Sampler2DRectShadow);
224 ADD_TYPE(Sampler1DArrayShadow);
225 ADD_TYPE(Sampler2DArrayShadow);
226 ADD_TYPE(SamplerCubeArrayShadow);
227 ADD_TYPE(GSampler2DArrayShadow);
228 ADD_TYPE(GSamplerCubeArrayShadow);
Ethan Nicholasc9472af2017-10-10 16:30:21 -0400229 ADD_TYPE(FragmentProcessor);
Stephen Whiteff5d7a22019-07-26 17:42:06 -0400230 ADD_TYPE(Sampler);
231 ADD_TYPE(Texture2D);
ethannicholasb3058bd2016-07-01 08:22:01 -0700232
Brian Osman28590d52020-03-23 16:59:08 -0400233 StringFragment fpAliasName("shader");
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400234 symbols->addWithoutOwnership(fpAliasName, fContext->fFragmentProcessor_Type.get());
Brian Osman28590d52020-03-23 16:59:08 -0400235
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700236 StringFragment skCapsName("sk_Caps");
John Stiles311dd9d2020-08-13 17:09:29 -0400237 fIRGenerator->fSymbolTable->add(
238 skCapsName,
239 std::make_unique<Variable>(/*offset=*/-1, Modifiers(), skCapsName,
Ethan Nicholas30d30222020-09-11 12:27:26 -0400240 fContext->fSkCaps_Type.get(), Variable::kGlobal_Storage));
Ethan Nicholas3605ace2016-11-21 15:59:48 -0500241
John Stiles810c8cf2020-08-26 19:46:27 -0400242 fIRGenerator->fIntrinsics = fGPUIntrinsics.get();
Ethan Nicholasdb80f692019-11-22 14:06:12 -0500243 std::vector<std::unique_ptr<ProgramElement>> gpuIntrinsics;
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400244 std::vector<std::unique_ptr<ProgramElement>> interpIntrinsics;
Brian Osmandd496172020-08-08 08:17:18 -0400245#if SKSL_STANDALONE
Ethan Nicholasb33fa3f2020-08-06 13:00:19 -0400246 this->processIncludeFile(Program::kFragment_Kind, SKSL_GPU_INCLUDE, symbols, &gpuIntrinsics,
247 &fGpuSymbolTable);
248 this->processIncludeFile(Program::kVertex_Kind, SKSL_VERT_INCLUDE, fGpuSymbolTable,
249 &fVertexInclude, &fVertexSymbolTable);
250 this->processIncludeFile(Program::kFragment_Kind, SKSL_FRAG_INCLUDE, fGpuSymbolTable,
251 &fFragmentInclude, &fFragmentSymbolTable);
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400252#else
253 {
254 Rehydrator rehydrator(fContext.get(), symbols, this, SKSL_INCLUDE_sksl_gpu,
255 SKSL_INCLUDE_sksl_gpu_LENGTH);
256 fGpuSymbolTable = rehydrator.symbolTable();
257 gpuIntrinsics = rehydrator.elements();
258 }
259 {
260 Rehydrator rehydrator(fContext.get(), fGpuSymbolTable, this, SKSL_INCLUDE_sksl_vert,
261 SKSL_INCLUDE_sksl_vert_LENGTH);
262 fVertexSymbolTable = rehydrator.symbolTable();
263 fVertexInclude = rehydrator.elements();
264 }
265 {
266 Rehydrator rehydrator(fContext.get(), fGpuSymbolTable, this, SKSL_INCLUDE_sksl_frag,
267 SKSL_INCLUDE_sksl_frag_LENGTH);
268 fFragmentSymbolTable = rehydrator.symbolTable();
269 fFragmentInclude = rehydrator.elements();
270 }
271#endif
John Stiles810c8cf2020-08-26 19:46:27 -0400272 grab_intrinsics(&gpuIntrinsics, fGPUIntrinsics.get());
273 grab_intrinsics(&interpIntrinsics, fInterpreterIntrinsics.get());
ethannicholasb3058bd2016-07-01 08:22:01 -0700274}
275
John Stiles656427a2020-08-27 15:26:26 -0400276Compiler::~Compiler() {}
ethannicholasb3058bd2016-07-01 08:22:01 -0700277
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400278void Compiler::loadGeometryIntrinsics() {
279 if (fGeometrySymbolTable) {
280 return;
281 }
Brian Osmandd496172020-08-08 08:17:18 -0400282 #if !SKSL_STANDALONE
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400283 {
284 Rehydrator rehydrator(fContext.get(), fGpuSymbolTable, this, SKSL_INCLUDE_sksl_geom,
285 SKSL_INCLUDE_sksl_geom_LENGTH);
286 fGeometrySymbolTable = rehydrator.symbolTable();
287 fGeometryInclude = rehydrator.elements();
288 }
289 #else
Ethan Nicholasb33fa3f2020-08-06 13:00:19 -0400290 this->processIncludeFile(Program::kGeometry_Kind, SKSL_GEOM_INCLUDE, fGpuSymbolTable,
291 &fGeometryInclude, &fGeometrySymbolTable);
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400292 #endif
293}
294
295void Compiler::loadPipelineIntrinsics() {
296 if (fPipelineSymbolTable) {
297 return;
298 }
Brian Osmandd496172020-08-08 08:17:18 -0400299 #if !SKSL_STANDALONE
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400300 {
301 Rehydrator rehydrator(fContext.get(), fGpuSymbolTable, this,
302 SKSL_INCLUDE_sksl_pipeline,
303 SKSL_INCLUDE_sksl_pipeline_LENGTH);
304 fPipelineSymbolTable = rehydrator.symbolTable();
305 fPipelineInclude = rehydrator.elements();
306 }
307 #else
308 this->processIncludeFile(Program::kPipelineStage_Kind, SKSL_PIPELINE_INCLUDE,
Ethan Nicholasb33fa3f2020-08-06 13:00:19 -0400309 fGpuSymbolTable, &fPipelineInclude, &fPipelineSymbolTable);
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400310 #endif
311}
312
313void Compiler::loadInterpreterIntrinsics() {
314 if (fInterpreterSymbolTable) {
315 return;
316 }
317 this->loadPipelineIntrinsics();
Brian Osmandd496172020-08-08 08:17:18 -0400318 #if !SKSL_STANDALONE
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400319 {
320 Rehydrator rehydrator(fContext.get(), fPipelineSymbolTable, this,
321 SKSL_INCLUDE_sksl_interp,
322 SKSL_INCLUDE_sksl_interp_LENGTH);
323 fInterpreterSymbolTable = rehydrator.symbolTable();
324 fInterpreterInclude = rehydrator.elements();
325 }
326 #else
327 this->processIncludeFile(Program::kGeneric_Kind, SKSL_INTERP_INCLUDE,
Ethan Nicholasb33fa3f2020-08-06 13:00:19 -0400328 fIRGenerator->fSymbolTable, &fInterpreterInclude,
329 &fInterpreterSymbolTable);
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400330 #endif
331}
332
Ethan Nicholasb33fa3f2020-08-06 13:00:19 -0400333void Compiler::processIncludeFile(Program::Kind kind, const char* path,
Ethan Nicholas8da1e652019-05-24 11:01:59 -0400334 std::shared_ptr<SymbolTable> base,
335 std::vector<std::unique_ptr<ProgramElement>>* outElements,
336 std::shared_ptr<SymbolTable>* outSymbolTable) {
Ethan Nicholasb33fa3f2020-08-06 13:00:19 -0400337 std::ifstream in(path);
338 std::string stdText{std::istreambuf_iterator<char>(in),
339 std::istreambuf_iterator<char>()};
340 if (in.rdstate()) {
341 printf("error reading %s\n", path);
342 abort();
343 }
344 if (!base) {
345 base = fIRGenerator->fSymbolTable;
346 }
347 SkASSERT(base);
348 const String* source = base->takeOwnershipOfString(std::make_unique<String>(stdText.c_str()));
349 fSource = source;
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400350 std::shared_ptr<SymbolTable> old = fIRGenerator->fSymbolTable;
351 if (base) {
352 fIRGenerator->fSymbolTable = std::move(base);
353 }
Ethan Nicholas8da1e652019-05-24 11:01:59 -0400354 Program::Settings settings;
Ethan Nicholasa11035b2019-11-26 16:27:47 -0500355#if !defined(SKSL_STANDALONE) & SK_SUPPORT_GPU
356 GrContextOptions opts;
357 GrShaderCaps caps(opts);
358 settings.fCaps = &caps;
359#endif
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400360 SkASSERT(fIRGenerator->fCanInline);
361 fIRGenerator->fCanInline = false;
362 fIRGenerator->start(&settings, nullptr, true);
Ethan Nicholasb33fa3f2020-08-06 13:00:19 -0400363 fIRGenerator->convertProgram(kind, source->c_str(), source->length(), outElements);
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400364 fIRGenerator->fCanInline = true;
Ethan Nicholas8da1e652019-05-24 11:01:59 -0400365 if (this->fErrorCount) {
366 printf("Unexpected errors: %s\n", this->fErrorText.c_str());
367 }
368 SkASSERT(!fErrorCount);
Ethan Nicholas8da1e652019-05-24 11:01:59 -0400369 *outSymbolTable = fIRGenerator->fSymbolTable;
Ethan Nicholasa11035b2019-11-26 16:27:47 -0500370#ifdef SK_DEBUG
371 fSource = nullptr;
372#endif
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400373 fIRGenerator->fSymbolTable = std::move(old);
Ethan Nicholas8da1e652019-05-24 11:01:59 -0400374}
375
ethannicholas22f939e2016-10-13 13:25:34 -0700376// add the definition created by assigning to the lvalue to the definition set
Ethan Nicholas86a43402017-01-19 13:32:00 -0500377void Compiler::addDefinition(const Expression* lvalue, std::unique_ptr<Expression>* expr,
378 DefinitionMap* definitions) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400379 switch (lvalue->kind()) {
380 case Expression::Kind::kVariableReference: {
John Stilesa5a97b42020-08-18 11:19:07 -0400381 const Variable& var = lvalue->as<VariableReference>().fVariable;
ethannicholas22f939e2016-10-13 13:25:34 -0700382 if (var.fStorage == Variable::kLocal_Storage) {
383 (*definitions)[&var] = expr;
384 }
385 break;
386 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400387 case Expression::Kind::kSwizzle:
ethannicholas22f939e2016-10-13 13:25:34 -0700388 // We consider the variable written to as long as at least some of its components have
389 // been written to. This will lead to some false negatives (we won't catch it if you
390 // write to foo.x and then read foo.y), but being stricter could lead to false positives
Mike Klein6ad99092016-10-26 10:35:22 -0400391 // (we write to foo.x, and then pass foo to a function which happens to only read foo.x,
392 // but since we pass foo as a whole it is flagged as an error) unless we perform a much
ethannicholas22f939e2016-10-13 13:25:34 -0700393 // more complicated whole-program analysis. This is probably good enough.
John Stilesa5a97b42020-08-18 11:19:07 -0400394 this->addDefinition(lvalue->as<Swizzle>().fBase.get(),
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400395 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
ethannicholas22f939e2016-10-13 13:25:34 -0700396 definitions);
397 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400398 case Expression::Kind::kIndex:
ethannicholas22f939e2016-10-13 13:25:34 -0700399 // see comments in Swizzle
John Stilesa5a97b42020-08-18 11:19:07 -0400400 this->addDefinition(lvalue->as<IndexExpression>().fBase.get(),
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400401 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
ethannicholas22f939e2016-10-13 13:25:34 -0700402 definitions);
403 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400404 case Expression::Kind::kFieldAccess:
ethannicholas22f939e2016-10-13 13:25:34 -0700405 // see comments in Swizzle
John Stilesa5a97b42020-08-18 11:19:07 -0400406 this->addDefinition(lvalue->as<FieldAccess>().fBase.get(),
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400407 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
ethannicholas22f939e2016-10-13 13:25:34 -0700408 definitions);
409 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400410 case Expression::Kind::kTernary:
Ethan Nicholasa583b812018-01-18 13:32:11 -0500411 // To simplify analysis, we just pretend that we write to both sides of the ternary.
412 // This allows for false positives (meaning we fail to detect that a variable might not
413 // have been assigned), but is preferable to false negatives.
John Stilesa5a97b42020-08-18 11:19:07 -0400414 this->addDefinition(lvalue->as<TernaryExpression>().fIfTrue.get(),
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400415 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
Ethan Nicholasa583b812018-01-18 13:32:11 -0500416 definitions);
John Stilesa5a97b42020-08-18 11:19:07 -0400417 this->addDefinition(lvalue->as<TernaryExpression>().fIfFalse.get(),
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400418 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
Ethan Nicholasa583b812018-01-18 13:32:11 -0500419 definitions);
420 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400421 case Expression::Kind::kExternalValue:
Ethan Nicholas91164d12019-05-15 15:29:54 -0400422 break;
ethannicholas22f939e2016-10-13 13:25:34 -0700423 default:
424 // not an lvalue, can't happen
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400425 SkASSERT(false);
ethannicholas22f939e2016-10-13 13:25:34 -0700426 }
427}
428
429// add local variables defined by this node to the set
Mike Klein6ad99092016-10-26 10:35:22 -0400430void Compiler::addDefinitions(const BasicBlock::Node& node,
Ethan Nicholas86a43402017-01-19 13:32:00 -0500431 DefinitionMap* definitions) {
ethannicholas22f939e2016-10-13 13:25:34 -0700432 switch (node.fKind) {
433 case BasicBlock::Node::kExpression_Kind: {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400434 SkASSERT(node.expression());
John Stilesa5a97b42020-08-18 11:19:07 -0400435 Expression* expr = node.expression()->get();
Ethan Nicholase6592142020-09-08 10:22:09 -0400436 switch (expr->kind()) {
437 case Expression::Kind::kBinary: {
John Stilesa5a97b42020-08-18 11:19:07 -0400438 BinaryExpression* b = &expr->as<BinaryExpression>();
Ethan Nicholas1d3e0e02020-09-16 15:19:24 -0400439 if (b->getOperator() == Token::Kind::TK_EQ) {
440 this->addDefinition(&b->left(), &b->rightPointer(), definitions);
441 } else if (Compiler::IsAssignment(b->getOperator())) {
Ethan Nicholas86a43402017-01-19 13:32:00 -0500442 this->addDefinition(
Ethan Nicholas1d3e0e02020-09-16 15:19:24 -0400443 &b->left(),
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400444 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
445 definitions);
Ethan Nicholas86a43402017-01-19 13:32:00 -0500446
447 }
448 break;
ethannicholas22f939e2016-10-13 13:25:34 -0700449 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400450 case Expression::Kind::kFunctionCall: {
John Stilesa5a97b42020-08-18 11:19:07 -0400451 const FunctionCall& c = expr->as<FunctionCall>();
Ethan Nicholasc6a19f12018-03-29 16:46:56 -0400452 for (size_t i = 0; i < c.fFunction.fParameters.size(); ++i) {
453 if (c.fFunction.fParameters[i]->fModifiers.fFlags & Modifiers::kOut_Flag) {
454 this->addDefinition(
455 c.fArguments[i].get(),
456 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
457 definitions);
458 }
459 }
460 break;
461 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400462 case Expression::Kind::kPrefix: {
John Stilesa5a97b42020-08-18 11:19:07 -0400463 const PrefixExpression* p = &expr->as<PrefixExpression>();
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400464 if (p->fOperator == Token::Kind::TK_MINUSMINUS ||
465 p->fOperator == Token::Kind::TK_PLUSPLUS) {
Ethan Nicholas86a43402017-01-19 13:32:00 -0500466 this->addDefinition(
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400467 p->fOperand.get(),
468 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
469 definitions);
Ethan Nicholas86a43402017-01-19 13:32:00 -0500470 }
471 break;
472 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400473 case Expression::Kind::kPostfix: {
John Stilesa5a97b42020-08-18 11:19:07 -0400474 const PostfixExpression* p = &expr->as<PostfixExpression>();
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400475 if (p->fOperator == Token::Kind::TK_MINUSMINUS ||
476 p->fOperator == Token::Kind::TK_PLUSPLUS) {
Ethan Nicholas86a43402017-01-19 13:32:00 -0500477 this->addDefinition(
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400478 p->fOperand.get(),
479 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
480 definitions);
Ethan Nicholas86a43402017-01-19 13:32:00 -0500481 }
482 break;
483 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400484 case Expression::Kind::kVariableReference: {
John Stilesa5a97b42020-08-18 11:19:07 -0400485 const VariableReference* v = &expr->as<VariableReference>();
Ethan Nicholascb670962017-04-20 19:31:52 -0400486 if (v->fRefKind != VariableReference::kRead_RefKind) {
487 this->addDefinition(
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400488 v,
489 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
490 definitions);
Ethan Nicholascb670962017-04-20 19:31:52 -0400491 }
John Stiles30212b72020-06-11 17:55:07 -0400492 break;
Ethan Nicholascb670962017-04-20 19:31:52 -0400493 }
Ethan Nicholas86a43402017-01-19 13:32:00 -0500494 default:
495 break;
ethannicholas22f939e2016-10-13 13:25:34 -0700496 }
497 break;
498 }
499 case BasicBlock::Node::kStatement_Kind: {
John Stilesa5a97b42020-08-18 11:19:07 -0400500 Statement* stmt = node.statement()->get();
Ethan Nicholase6592142020-09-08 10:22:09 -0400501 if (stmt->kind() == Statement::Kind::kVarDeclaration) {
John Stilesa5a97b42020-08-18 11:19:07 -0400502 VarDeclaration& vd = stmt->as<VarDeclaration>();
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000503 if (vd.fValue) {
504 (*definitions)[vd.fVar] = &vd.fValue;
ethannicholas22f939e2016-10-13 13:25:34 -0700505 }
506 }
507 break;
508 }
509 }
510}
511
512void Compiler::scanCFG(CFG* cfg, BlockId blockId, std::set<BlockId>* workList) {
513 BasicBlock& block = cfg->fBlocks[blockId];
514
515 // compute definitions after this block
Ethan Nicholas86a43402017-01-19 13:32:00 -0500516 DefinitionMap after = block.fBefore;
ethannicholas22f939e2016-10-13 13:25:34 -0700517 for (const BasicBlock::Node& n : block.fNodes) {
518 this->addDefinitions(n, &after);
519 }
520
521 // propagate definitions to exits
522 for (BlockId exitId : block.fExits) {
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400523 if (exitId == blockId) {
524 continue;
525 }
ethannicholas22f939e2016-10-13 13:25:34 -0700526 BasicBlock& exit = cfg->fBlocks[exitId];
527 for (const auto& pair : after) {
Ethan Nicholas86a43402017-01-19 13:32:00 -0500528 std::unique_ptr<Expression>* e1 = pair.second;
529 auto found = exit.fBefore.find(pair.first);
530 if (found == exit.fBefore.end()) {
531 // exit has no definition for it, just copy it
532 workList->insert(exitId);
ethannicholas22f939e2016-10-13 13:25:34 -0700533 exit.fBefore[pair.first] = e1;
534 } else {
Ethan Nicholas86a43402017-01-19 13:32:00 -0500535 // exit has a (possibly different) value already defined
536 std::unique_ptr<Expression>* e2 = exit.fBefore[pair.first];
ethannicholas22f939e2016-10-13 13:25:34 -0700537 if (e1 != e2) {
538 // definition has changed, merge and add exit block to worklist
539 workList->insert(exitId);
Ethan Nicholasaf197692017-02-27 13:26:45 -0500540 if (e1 && e2) {
541 exit.fBefore[pair.first] =
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400542 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression;
Ethan Nicholasaf197692017-02-27 13:26:45 -0500543 } else {
544 exit.fBefore[pair.first] = nullptr;
545 }
ethannicholas22f939e2016-10-13 13:25:34 -0700546 }
547 }
548 }
549 }
550}
551
552// returns a map which maps all local variables in the function to null, indicating that their value
553// is initially unknown
Ethan Nicholas86a43402017-01-19 13:32:00 -0500554static DefinitionMap compute_start_state(const CFG& cfg) {
555 DefinitionMap result;
Mike Klein6ad99092016-10-26 10:35:22 -0400556 for (const auto& block : cfg.fBlocks) {
557 for (const auto& node : block.fNodes) {
ethannicholas22f939e2016-10-13 13:25:34 -0700558 if (node.fKind == BasicBlock::Node::kStatement_Kind) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400559 SkASSERT(node.statement());
Ethan Nicholascb670962017-04-20 19:31:52 -0400560 const Statement* s = node.statement()->get();
Ethan Nicholase6592142020-09-08 10:22:09 -0400561 if (s->kind() == Statement::Kind::kVarDeclarations) {
John Stilesa5a97b42020-08-18 11:19:07 -0400562 const VarDeclarationsStatement* vd = &s->as<VarDeclarationsStatement>();
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000563 for (const auto& decl : vd->fDeclaration->fVars) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400564 if (decl->kind() == Statement::Kind::kVarDeclaration) {
John Stilesa5a97b42020-08-18 11:19:07 -0400565 result[decl->as<VarDeclaration>().fVar] = nullptr;
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000566 }
Mike Klein6ad99092016-10-26 10:35:22 -0400567 }
ethannicholas22f939e2016-10-13 13:25:34 -0700568 }
569 }
570 }
571 }
572 return result;
573}
574
Ethan Nicholascb670962017-04-20 19:31:52 -0400575/**
576 * Returns true if assigning to this lvalue has no effect.
577 */
578static bool is_dead(const Expression& lvalue) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400579 switch (lvalue.kind()) {
580 case Expression::Kind::kVariableReference:
John Stilesa5a97b42020-08-18 11:19:07 -0400581 return lvalue.as<VariableReference>().fVariable.dead();
Ethan Nicholase6592142020-09-08 10:22:09 -0400582 case Expression::Kind::kSwizzle:
John Stilesa5a97b42020-08-18 11:19:07 -0400583 return is_dead(*lvalue.as<Swizzle>().fBase);
Ethan Nicholase6592142020-09-08 10:22:09 -0400584 case Expression::Kind::kFieldAccess:
John Stilesa5a97b42020-08-18 11:19:07 -0400585 return is_dead(*lvalue.as<FieldAccess>().fBase);
Ethan Nicholase6592142020-09-08 10:22:09 -0400586 case Expression::Kind::kIndex: {
John Stilesa5a97b42020-08-18 11:19:07 -0400587 const IndexExpression& idx = lvalue.as<IndexExpression>();
Ethan Nicholas2a099da2020-01-02 14:40:54 -0500588 return is_dead(*idx.fBase) &&
589 !idx.fIndex->hasProperty(Expression::Property::kSideEffects);
Ethan Nicholascb670962017-04-20 19:31:52 -0400590 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400591 case Expression::Kind::kTernary: {
John Stilesa5a97b42020-08-18 11:19:07 -0400592 const TernaryExpression& t = lvalue.as<TernaryExpression>();
Ethan Nicholasa583b812018-01-18 13:32:11 -0500593 return !t.fTest->hasSideEffects() && is_dead(*t.fIfTrue) && is_dead(*t.fIfFalse);
594 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400595 case Expression::Kind::kExternalValue:
Ethan Nicholas91164d12019-05-15 15:29:54 -0400596 return false;
Ethan Nicholascb670962017-04-20 19:31:52 -0400597 default:
Ethan Nicholas2a099da2020-01-02 14:40:54 -0500598#ifdef SK_DEBUG
Ethan Nicholascb670962017-04-20 19:31:52 -0400599 ABORT("invalid lvalue: %s\n", lvalue.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -0500600#endif
601 return false;
Ethan Nicholascb670962017-04-20 19:31:52 -0400602 }
603}
ethannicholas22f939e2016-10-13 13:25:34 -0700604
Ethan Nicholascb670962017-04-20 19:31:52 -0400605/**
606 * Returns true if this is an assignment which can be collapsed down to just the right hand side due
607 * to a dead target and lack of side effects on the left hand side.
608 */
609static bool dead_assignment(const BinaryExpression& b) {
Ethan Nicholas1d3e0e02020-09-16 15:19:24 -0400610 if (!Compiler::IsAssignment(b.getOperator())) {
Ethan Nicholascb670962017-04-20 19:31:52 -0400611 return false;
612 }
Ethan Nicholas1d3e0e02020-09-16 15:19:24 -0400613 return is_dead(b.left());
Ethan Nicholascb670962017-04-20 19:31:52 -0400614}
615
616void Compiler::computeDataFlow(CFG* cfg) {
617 cfg->fBlocks[cfg->fStart].fBefore = compute_start_state(*cfg);
ethannicholas22f939e2016-10-13 13:25:34 -0700618 std::set<BlockId> workList;
Ethan Nicholascb670962017-04-20 19:31:52 -0400619 for (BlockId i = 0; i < cfg->fBlocks.size(); i++) {
ethannicholas22f939e2016-10-13 13:25:34 -0700620 workList.insert(i);
621 }
622 while (workList.size()) {
623 BlockId next = *workList.begin();
624 workList.erase(workList.begin());
Ethan Nicholascb670962017-04-20 19:31:52 -0400625 this->scanCFG(cfg, next, &workList);
ethannicholas22f939e2016-10-13 13:25:34 -0700626 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400627}
628
629/**
630 * Attempts to replace the expression pointed to by iter with a new one (in both the CFG and the
631 * IR). If the expression can be cleanly removed, returns true and updates the iterator to point to
632 * the newly-inserted element. Otherwise updates only the IR and returns false (and the CFG will
633 * need to be regenerated).
634 */
John Stilesafbf8992020-08-18 10:08:21 -0400635static bool try_replace_expression(BasicBlock* b,
636 std::vector<BasicBlock::Node>::iterator* iter,
637 std::unique_ptr<Expression>* newExpression) {
Ethan Nicholascb670962017-04-20 19:31:52 -0400638 std::unique_ptr<Expression>* target = (*iter)->expression();
639 if (!b->tryRemoveExpression(iter)) {
640 *target = std::move(*newExpression);
641 return false;
642 }
643 *target = std::move(*newExpression);
644 return b->tryInsertExpression(iter, target);
645}
646
647/**
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400648 * Returns true if the expression is a constant numeric literal with the specified value, or a
649 * constant vector with all elements equal to the specified value.
Ethan Nicholascb670962017-04-20 19:31:52 -0400650 */
John Stiles9d944232020-08-19 09:56:49 -0400651template <typename T = double>
652static bool is_constant(const Expression& expr, T value) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400653 switch (expr.kind()) {
654 case Expression::Kind::kIntLiteral:
John Stiles81365af2020-08-18 09:24:00 -0400655 return expr.as<IntLiteral>().fValue == value;
John Stiles9d944232020-08-19 09:56:49 -0400656
Ethan Nicholase6592142020-09-08 10:22:09 -0400657 case Expression::Kind::kFloatLiteral:
John Stiles81365af2020-08-18 09:24:00 -0400658 return expr.as<FloatLiteral>().fValue == value;
John Stiles9d944232020-08-19 09:56:49 -0400659
Ethan Nicholase6592142020-09-08 10:22:09 -0400660 case Expression::Kind::kConstructor: {
John Stiles9d944232020-08-19 09:56:49 -0400661 const Constructor& constructor = expr.as<Constructor>();
662 if (constructor.isCompileTimeConstant()) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400663 const Type& constructorType = constructor.type();
664 bool isFloat = constructorType.columns() > 1
665 ? constructorType.componentType().isFloat()
666 : constructorType.isFloat();
667 switch (constructorType.typeKind()) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400668 case Type::TypeKind::kVector:
Ethan Nicholas30d30222020-09-11 12:27:26 -0400669 for (int i = 0; i < constructorType.columns(); ++i) {
John Stiles9d944232020-08-19 09:56:49 -0400670 if (isFloat) {
671 if (constructor.getFVecComponent(i) != value) {
672 return false;
673 }
674 } else {
675 if (constructor.getIVecComponent(i) != value) {
676 return false;
677 }
678 }
Ethan Nicholasd188c182019-06-10 15:55:38 -0400679 }
John Stiles9d944232020-08-19 09:56:49 -0400680 return true;
681
Ethan Nicholase6592142020-09-08 10:22:09 -0400682 case Type::TypeKind::kScalar:
John Stiles9d944232020-08-19 09:56:49 -0400683 SkASSERT(constructor.fArguments.size() == 1);
684 return is_constant<T>(*constructor.fArguments[0], value);
685
686 default:
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400687 return false;
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400688 }
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400689 }
690 return false;
691 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400692 default:
693 return false;
694 }
695}
696
697/**
698 * Collapses the binary expression pointed to by iter down to just the right side (in both the IR
699 * and CFG structures).
700 */
John Stilesafbf8992020-08-18 10:08:21 -0400701static void delete_left(BasicBlock* b,
702 std::vector<BasicBlock::Node>::iterator* iter,
703 bool* outUpdated,
704 bool* outNeedsRescan) {
Ethan Nicholascb670962017-04-20 19:31:52 -0400705 *outUpdated = true;
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400706 std::unique_ptr<Expression>* target = (*iter)->expression();
John Stilesa5a97b42020-08-18 11:19:07 -0400707 BinaryExpression& bin = (*target)->as<BinaryExpression>();
Ethan Nicholas1d3e0e02020-09-16 15:19:24 -0400708 Expression& left = bin.left();
709 std::unique_ptr<Expression>& rightPointer = bin.rightPointer();
710 SkASSERT(!left.hasSideEffects());
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400711 bool result;
Ethan Nicholas1d3e0e02020-09-16 15:19:24 -0400712 if (bin.getOperator() == Token::Kind::TK_EQ) {
713 result = b->tryRemoveLValueBefore(iter, &left);
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400714 } else {
Ethan Nicholas1d3e0e02020-09-16 15:19:24 -0400715 result = b->tryRemoveExpressionBefore(iter, &left);
Ethan Nicholascb670962017-04-20 19:31:52 -0400716 }
Ethan Nicholas1d3e0e02020-09-16 15:19:24 -0400717 *target = std::move(rightPointer);
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400718 if (!result) {
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400719 *outNeedsRescan = true;
720 return;
721 }
722 if (*iter == b->fNodes.begin()) {
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400723 *outNeedsRescan = true;
724 return;
725 }
726 --(*iter);
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400727 if ((*iter)->fKind != BasicBlock::Node::kExpression_Kind ||
Ethan Nicholas1d3e0e02020-09-16 15:19:24 -0400728 (*iter)->expression() != &rightPointer) {
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400729 *outNeedsRescan = true;
730 return;
731 }
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400732 *iter = b->fNodes.erase(*iter);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400733 SkASSERT((*iter)->expression() == target);
Ethan Nicholascb670962017-04-20 19:31:52 -0400734}
735
736/**
737 * Collapses the binary expression pointed to by iter down to just the left side (in both the IR and
738 * CFG structures).
739 */
John Stilesafbf8992020-08-18 10:08:21 -0400740static void delete_right(BasicBlock* b,
741 std::vector<BasicBlock::Node>::iterator* iter,
742 bool* outUpdated,
743 bool* outNeedsRescan) {
Ethan Nicholascb670962017-04-20 19:31:52 -0400744 *outUpdated = true;
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400745 std::unique_ptr<Expression>* target = (*iter)->expression();
John Stilesa5a97b42020-08-18 11:19:07 -0400746 BinaryExpression& bin = (*target)->as<BinaryExpression>();
Ethan Nicholas1d3e0e02020-09-16 15:19:24 -0400747 std::unique_ptr<Expression>& leftPointer = bin.leftPointer();
748 Expression& right = bin.right();
749 SkASSERT(!right.hasSideEffects());
750 if (!b->tryRemoveExpressionBefore(iter, &right)) {
751 *target = std::move(leftPointer);
Ethan Nicholascb670962017-04-20 19:31:52 -0400752 *outNeedsRescan = true;
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400753 return;
Ethan Nicholascb670962017-04-20 19:31:52 -0400754 }
Ethan Nicholas1d3e0e02020-09-16 15:19:24 -0400755 *target = std::move(leftPointer);
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400756 if (*iter == b->fNodes.begin()) {
757 *outNeedsRescan = true;
758 return;
759 }
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400760 --(*iter);
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400761 if (((*iter)->fKind != BasicBlock::Node::kExpression_Kind ||
Ethan Nicholas1d3e0e02020-09-16 15:19:24 -0400762 (*iter)->expression() != &leftPointer)) {
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400763 *outNeedsRescan = true;
764 return;
765 }
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400766 *iter = b->fNodes.erase(*iter);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400767 SkASSERT((*iter)->expression() == target);
Ethan Nicholascb670962017-04-20 19:31:52 -0400768}
769
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400770/**
771 * Constructs the specified type using a single argument.
772 */
Ethan Nicholas30d30222020-09-11 12:27:26 -0400773static std::unique_ptr<Expression> construct(const Type* type, std::unique_ptr<Expression> v) {
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400774 std::vector<std::unique_ptr<Expression>> args;
775 args.push_back(std::move(v));
Ethan Nicholase6592142020-09-08 10:22:09 -0400776 std::unique_ptr<Expression> result = std::make_unique<Constructor>(-1, type, std::move(args));
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400777 return result;
778}
779
780/**
781 * Used in the implementations of vectorize_left and vectorize_right. Given a vector type and an
782 * expression x, deletes the expression pointed to by iter and replaces it with <type>(x).
783 */
784static void vectorize(BasicBlock* b,
785 std::vector<BasicBlock::Node>::iterator* iter,
786 const Type& type,
787 std::unique_ptr<Expression>* otherExpression,
788 bool* outUpdated,
789 bool* outNeedsRescan) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400790 SkASSERT((*(*iter)->expression())->kind() == Expression::Kind::kBinary);
791 SkASSERT(type.typeKind() == Type::TypeKind::kVector);
Ethan Nicholas30d30222020-09-11 12:27:26 -0400792 SkASSERT((*otherExpression)->type().typeKind() == Type::TypeKind::kScalar);
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400793 *outUpdated = true;
794 std::unique_ptr<Expression>* target = (*iter)->expression();
795 if (!b->tryRemoveExpression(iter)) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400796 *target = construct(&type, std::move(*otherExpression));
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400797 *outNeedsRescan = true;
798 } else {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400799 *target = construct(&type, std::move(*otherExpression));
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400800 if (!b->tryInsertExpression(iter, target)) {
801 *outNeedsRescan = true;
802 }
803 }
804}
805
806/**
807 * Given a binary expression of the form x <op> vec<n>(y), deletes the right side and vectorizes the
808 * left to yield vec<n>(x).
809 */
810static void vectorize_left(BasicBlock* b,
811 std::vector<BasicBlock::Node>::iterator* iter,
812 bool* outUpdated,
813 bool* outNeedsRescan) {
John Stilesa5a97b42020-08-18 11:19:07 -0400814 BinaryExpression& bin = (*(*iter)->expression())->as<BinaryExpression>();
Ethan Nicholas1d3e0e02020-09-16 15:19:24 -0400815 vectorize(b, iter, bin.right().type(), &bin.leftPointer(), outUpdated, outNeedsRescan);
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400816}
817
818/**
819 * Given a binary expression of the form vec<n>(x) <op> y, deletes the left side and vectorizes the
820 * right to yield vec<n>(y).
821 */
822static void vectorize_right(BasicBlock* b,
823 std::vector<BasicBlock::Node>::iterator* iter,
824 bool* outUpdated,
825 bool* outNeedsRescan) {
John Stilesa5a97b42020-08-18 11:19:07 -0400826 BinaryExpression& bin = (*(*iter)->expression())->as<BinaryExpression>();
Ethan Nicholas1d3e0e02020-09-16 15:19:24 -0400827 vectorize(b, iter, bin.left().type(), &bin.rightPointer(), outUpdated, outNeedsRescan);
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400828}
829
830// Mark that an expression which we were writing to is no longer being written to
John Stilesa5a97b42020-08-18 11:19:07 -0400831static void clear_write(Expression& expr) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400832 switch (expr.kind()) {
833 case Expression::Kind::kVariableReference: {
John Stilesa5a97b42020-08-18 11:19:07 -0400834 expr.as<VariableReference>().setRefKind(VariableReference::kRead_RefKind);
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400835 break;
836 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400837 case Expression::Kind::kFieldAccess:
John Stilesa5a97b42020-08-18 11:19:07 -0400838 clear_write(*expr.as<FieldAccess>().fBase);
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400839 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400840 case Expression::Kind::kSwizzle:
John Stilesa5a97b42020-08-18 11:19:07 -0400841 clear_write(*expr.as<Swizzle>().fBase);
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400842 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400843 case Expression::Kind::kIndex:
John Stilesa5a97b42020-08-18 11:19:07 -0400844 clear_write(*expr.as<IndexExpression>().fBase);
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400845 break;
846 default:
847 ABORT("shouldn't be writing to this kind of expression\n");
848 break;
849 }
850}
851
Ethan Nicholascb670962017-04-20 19:31:52 -0400852void Compiler::simplifyExpression(DefinitionMap& definitions,
853 BasicBlock& b,
854 std::vector<BasicBlock::Node>::iterator* iter,
855 std::unordered_set<const Variable*>* undefinedVariables,
856 bool* outUpdated,
857 bool* outNeedsRescan) {
858 Expression* expr = (*iter)->expression()->get();
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400859 SkASSERT(expr);
Ethan Nicholascb670962017-04-20 19:31:52 -0400860 if ((*iter)->fConstantPropagation) {
861 std::unique_ptr<Expression> optimized = expr->constantPropagate(*fIRGenerator, definitions);
862 if (optimized) {
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400863 *outUpdated = true;
Ethan Nicholas30d30222020-09-11 12:27:26 -0400864 optimized = fIRGenerator->coerce(std::move(optimized), expr->type());
Ethan Nicholas1d881522020-09-11 09:32:54 -0400865 SkASSERT(optimized);
Ethan Nicholascb670962017-04-20 19:31:52 -0400866 if (!try_replace_expression(&b, iter, &optimized)) {
867 *outNeedsRescan = true;
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400868 return;
Ethan Nicholascb670962017-04-20 19:31:52 -0400869 }
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400870 SkASSERT((*iter)->fKind == BasicBlock::Node::kExpression_Kind);
Ethan Nicholascb670962017-04-20 19:31:52 -0400871 expr = (*iter)->expression()->get();
Ethan Nicholascb670962017-04-20 19:31:52 -0400872 }
873 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400874 switch (expr->kind()) {
875 case Expression::Kind::kVariableReference: {
John Stilesa5a97b42020-08-18 11:19:07 -0400876 const VariableReference& ref = expr->as<VariableReference>();
Ethan Nicholas8f7e28f2018-03-26 14:24:27 -0400877 const Variable& var = ref.fVariable;
878 if (ref.refKind() != VariableReference::kWrite_RefKind &&
879 ref.refKind() != VariableReference::kPointer_RefKind &&
880 var.fStorage == Variable::kLocal_Storage && !definitions[&var] &&
Ethan Nicholascb670962017-04-20 19:31:52 -0400881 (*undefinedVariables).find(&var) == (*undefinedVariables).end()) {
882 (*undefinedVariables).insert(&var);
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000883 this->error(expr->fOffset,
884 "'" + var.fName + "' has not been assigned");
Ethan Nicholascb670962017-04-20 19:31:52 -0400885 }
886 break;
887 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400888 case Expression::Kind::kTernary: {
John Stiles403a3632020-08-20 12:11:48 -0400889 TernaryExpression* t = &expr->as<TernaryExpression>();
Ethan Nicholase6592142020-09-08 10:22:09 -0400890 if (t->fTest->kind() == Expression::Kind::kBoolLiteral) {
Ethan Nicholascb670962017-04-20 19:31:52 -0400891 // ternary has a constant test, replace it with either the true or
892 // false branch
John Stiles403a3632020-08-20 12:11:48 -0400893 if (t->fTest->as<BoolLiteral>().fValue) {
Ethan Nicholascb670962017-04-20 19:31:52 -0400894 (*iter)->setExpression(std::move(t->fIfTrue));
895 } else {
896 (*iter)->setExpression(std::move(t->fIfFalse));
897 }
898 *outUpdated = true;
899 *outNeedsRescan = true;
900 }
901 break;
902 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400903 case Expression::Kind::kBinary: {
John Stiles403a3632020-08-20 12:11:48 -0400904 BinaryExpression* bin = &expr->as<BinaryExpression>();
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400905 if (dead_assignment(*bin)) {
906 delete_left(&b, iter, outUpdated, outNeedsRescan);
907 break;
908 }
Ethan Nicholas1d3e0e02020-09-16 15:19:24 -0400909 Expression& left = bin->left();
910 Expression& right = bin->right();
911 const Type& leftType = left.type();
912 const Type& rightType = right.type();
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400913 // collapse useless expressions like x * 1 or x + 0
Ethan Nicholas30d30222020-09-11 12:27:26 -0400914 if (((leftType.typeKind() != Type::TypeKind::kScalar) &&
915 (leftType.typeKind() != Type::TypeKind::kVector)) ||
916 ((rightType.typeKind() != Type::TypeKind::kScalar) &&
917 (rightType.typeKind() != Type::TypeKind::kVector))) {
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400918 break;
919 }
Ethan Nicholas1d3e0e02020-09-16 15:19:24 -0400920 switch (bin->getOperator()) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400921 case Token::Kind::TK_STAR:
Ethan Nicholas1d3e0e02020-09-16 15:19:24 -0400922 if (is_constant(left, 1)) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400923 if (leftType.typeKind() == Type::TypeKind::kVector &&
924 rightType.typeKind() == Type::TypeKind::kScalar) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400925 // float4(1) * x -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400926 vectorize_right(&b, iter, outUpdated, outNeedsRescan);
927 } else {
928 // 1 * x -> x
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400929 // 1 * float4(x) -> float4(x)
930 // float4(1) * float4(x) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400931 delete_left(&b, iter, outUpdated, outNeedsRescan);
932 }
933 }
Ethan Nicholas1d3e0e02020-09-16 15:19:24 -0400934 else if (is_constant(left, 0)) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400935 if (leftType.typeKind() == Type::TypeKind::kScalar &&
936 rightType.typeKind() == Type::TypeKind::kVector &&
Ethan Nicholas1d3e0e02020-09-16 15:19:24 -0400937 !right.hasSideEffects()) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400938 // 0 * float4(x) -> float4(0)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400939 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
940 } else {
941 // 0 * x -> 0
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400942 // float4(0) * x -> float4(0)
943 // float4(0) * float4(x) -> float4(0)
Ethan Nicholas1d3e0e02020-09-16 15:19:24 -0400944 if (!right.hasSideEffects()) {
Ethan Nicholas51493ee2017-12-11 12:34:33 -0500945 delete_right(&b, iter, outUpdated, outNeedsRescan);
946 }
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400947 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400948 }
Ethan Nicholas1d3e0e02020-09-16 15:19:24 -0400949 else if (is_constant(right, 1)) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400950 if (leftType.typeKind() == Type::TypeKind::kScalar &&
951 rightType.typeKind() == Type::TypeKind::kVector) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400952 // x * float4(1) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400953 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
954 } else {
955 // x * 1 -> x
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400956 // float4(x) * 1 -> float4(x)
957 // float4(x) * float4(1) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400958 delete_right(&b, iter, outUpdated, outNeedsRescan);
959 }
960 }
Ethan Nicholas1d3e0e02020-09-16 15:19:24 -0400961 else if (is_constant(right, 0)) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400962 if (leftType.typeKind() == Type::TypeKind::kVector &&
963 rightType.typeKind() == Type::TypeKind::kScalar &&
Ethan Nicholas1d3e0e02020-09-16 15:19:24 -0400964 !left.hasSideEffects()) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400965 // float4(x) * 0 -> float4(0)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400966 vectorize_right(&b, iter, outUpdated, outNeedsRescan);
967 } else {
968 // x * 0 -> 0
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400969 // x * float4(0) -> float4(0)
970 // float4(x) * float4(0) -> float4(0)
Ethan Nicholas1d3e0e02020-09-16 15:19:24 -0400971 if (!left.hasSideEffects()) {
Ethan Nicholas51493ee2017-12-11 12:34:33 -0500972 delete_left(&b, iter, outUpdated, outNeedsRescan);
973 }
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400974 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400975 }
976 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400977 case Token::Kind::TK_PLUS:
Ethan Nicholas1d3e0e02020-09-16 15:19:24 -0400978 if (is_constant(left, 0)) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400979 if (leftType.typeKind() == Type::TypeKind::kVector &&
980 rightType.typeKind() == Type::TypeKind::kScalar) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400981 // float4(0) + x -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400982 vectorize_right(&b, iter, outUpdated, outNeedsRescan);
983 } else {
984 // 0 + x -> x
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400985 // 0 + float4(x) -> float4(x)
986 // float4(0) + float4(x) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400987 delete_left(&b, iter, outUpdated, outNeedsRescan);
988 }
Ethan Nicholas1d3e0e02020-09-16 15:19:24 -0400989 } else if (is_constant(right, 0)) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400990 if (leftType.typeKind() == Type::TypeKind::kScalar &&
991 rightType.typeKind() == Type::TypeKind::kVector) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400992 // x + float4(0) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400993 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
994 } else {
995 // x + 0 -> x
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400996 // float4(x) + 0 -> float4(x)
997 // float4(x) + float4(0) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400998 delete_right(&b, iter, outUpdated, outNeedsRescan);
999 }
Ethan Nicholas56e42712017-04-21 10:23:37 -04001000 }
1001 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001002 case Token::Kind::TK_MINUS:
Ethan Nicholas1d3e0e02020-09-16 15:19:24 -04001003 if (is_constant(right, 0)) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04001004 if (leftType.typeKind() == Type::TypeKind::kScalar &&
1005 rightType.typeKind() == Type::TypeKind::kVector) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -04001006 // x - float4(0) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -04001007 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
1008 } else {
1009 // x - 0 -> x
Ethan Nicholas5af9ea32017-07-28 15:19:46 -04001010 // float4(x) - 0 -> float4(x)
1011 // float4(x) - float4(0) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -04001012 delete_right(&b, iter, outUpdated, outNeedsRescan);
1013 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001014 }
1015 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001016 case Token::Kind::TK_SLASH:
Ethan Nicholas1d3e0e02020-09-16 15:19:24 -04001017 if (is_constant(right, 1)) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04001018 if (leftType.typeKind() == Type::TypeKind::kScalar &&
1019 rightType.typeKind() == Type::TypeKind::kVector) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -04001020 // x / float4(1) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -04001021 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
1022 } else {
1023 // x / 1 -> x
Ethan Nicholas5af9ea32017-07-28 15:19:46 -04001024 // float4(x) / 1 -> float4(x)
1025 // float4(x) / float4(1) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -04001026 delete_right(&b, iter, outUpdated, outNeedsRescan);
1027 }
Ethan Nicholas1d3e0e02020-09-16 15:19:24 -04001028 } else if (is_constant(left, 0)) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04001029 if (leftType.typeKind() == Type::TypeKind::kScalar &&
1030 rightType.typeKind() == Type::TypeKind::kVector &&
Ethan Nicholas1d3e0e02020-09-16 15:19:24 -04001031 !right.hasSideEffects()) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -04001032 // 0 / float4(x) -> float4(0)
Ethan Nicholasfe53e582017-04-27 16:24:51 -04001033 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
1034 } else {
1035 // 0 / x -> 0
Ethan Nicholas5af9ea32017-07-28 15:19:46 -04001036 // float4(0) / x -> float4(0)
1037 // float4(0) / float4(x) -> float4(0)
Ethan Nicholas1d3e0e02020-09-16 15:19:24 -04001038 if (!right.hasSideEffects()) {
Ethan Nicholas51493ee2017-12-11 12:34:33 -05001039 delete_right(&b, iter, outUpdated, outNeedsRescan);
1040 }
Ethan Nicholasfe53e582017-04-27 16:24:51 -04001041 }
1042 }
1043 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001044 case Token::Kind::TK_PLUSEQ:
Ethan Nicholas1d3e0e02020-09-16 15:19:24 -04001045 if (is_constant(right, 0)) {
1046 clear_write(left);
Ethan Nicholasfe53e582017-04-27 16:24:51 -04001047 delete_right(&b, iter, outUpdated, outNeedsRescan);
1048 }
1049 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001050 case Token::Kind::TK_MINUSEQ:
Ethan Nicholas1d3e0e02020-09-16 15:19:24 -04001051 if (is_constant(right, 0)) {
1052 clear_write(left);
Ethan Nicholasfe53e582017-04-27 16:24:51 -04001053 delete_right(&b, iter, outUpdated, outNeedsRescan);
1054 }
1055 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001056 case Token::Kind::TK_STAREQ:
Ethan Nicholas1d3e0e02020-09-16 15:19:24 -04001057 if (is_constant(right, 1)) {
1058 clear_write(left);
Ethan Nicholasfe53e582017-04-27 16:24:51 -04001059 delete_right(&b, iter, outUpdated, outNeedsRescan);
1060 }
1061 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001062 case Token::Kind::TK_SLASHEQ:
Ethan Nicholas1d3e0e02020-09-16 15:19:24 -04001063 if (is_constant(right, 1)) {
1064 clear_write(left);
Ethan Nicholascb670962017-04-20 19:31:52 -04001065 delete_right(&b, iter, outUpdated, outNeedsRescan);
1066 }
1067 break;
1068 default:
1069 break;
1070 }
Ethan Nicholas409f6f02019-09-17 12:34:39 -04001071 break;
1072 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001073 case Expression::Kind::kSwizzle: {
John Stiles403a3632020-08-20 12:11:48 -04001074 Swizzle& s = expr->as<Swizzle>();
Ethan Nicholas409f6f02019-09-17 12:34:39 -04001075 // detect identity swizzles like foo.rgba
Ethan Nicholas30d30222020-09-11 12:27:26 -04001076 if ((int) s.fComponents.size() == s.fBase->type().columns()) {
Ethan Nicholas409f6f02019-09-17 12:34:39 -04001077 bool identity = true;
1078 for (int i = 0; i < (int) s.fComponents.size(); ++i) {
1079 if (s.fComponents[i] != i) {
1080 identity = false;
1081 break;
1082 }
1083 }
1084 if (identity) {
1085 *outUpdated = true;
1086 if (!try_replace_expression(&b, iter, &s.fBase)) {
1087 *outNeedsRescan = true;
1088 return;
1089 }
1090 SkASSERT((*iter)->fKind == BasicBlock::Node::kExpression_Kind);
1091 break;
1092 }
1093 }
1094 // detect swizzles of swizzles, e.g. replace foo.argb.r000 with foo.a000
Ethan Nicholase6592142020-09-08 10:22:09 -04001095 if (s.fBase->kind() == Expression::Kind::kSwizzle) {
John Stilesa5a97b42020-08-18 11:19:07 -04001096 Swizzle& base = s.fBase->as<Swizzle>();
Ethan Nicholas409f6f02019-09-17 12:34:39 -04001097 std::vector<int> final;
1098 for (int c : s.fComponents) {
Brian Osman25647672020-09-15 15:16:56 -04001099 final.push_back(base.fComponents[c]);
Ethan Nicholas409f6f02019-09-17 12:34:39 -04001100 }
1101 *outUpdated = true;
1102 std::unique_ptr<Expression> replacement(new Swizzle(*fContext, base.fBase->clone(),
1103 std::move(final)));
1104 if (!try_replace_expression(&b, iter, &replacement)) {
1105 *outNeedsRescan = true;
1106 return;
1107 }
1108 SkASSERT((*iter)->fKind == BasicBlock::Node::kExpression_Kind);
Ethan Nicholas409f6f02019-09-17 12:34:39 -04001109 }
John Stiles30212b72020-06-11 17:55:07 -04001110 break;
Ethan Nicholascb670962017-04-20 19:31:52 -04001111 }
1112 default:
1113 break;
1114 }
1115}
1116
John Stiles92219b42020-06-15 12:32:24 -04001117// Returns true if this statement could potentially execute a break at the current level. We ignore
1118// nested loops and switches, since any breaks inside of them will merely break the loop / switch.
John Stilesb92641c2020-08-31 18:09:01 -04001119static bool contains_conditional_break(Statement& stmt) {
1120 class ContainsConditionalBreak : public ProgramVisitor {
1121 public:
1122 bool visitStatement(const Statement& stmt) override {
Ethan Nicholase6592142020-09-08 10:22:09 -04001123 switch (stmt.kind()) {
1124 case Statement::Kind::kBlock:
John Stilesb92641c2020-08-31 18:09:01 -04001125 return this->INHERITED::visitStatement(stmt);
1126
Ethan Nicholase6592142020-09-08 10:22:09 -04001127 case Statement::Kind::kBreak:
John Stilesb92641c2020-08-31 18:09:01 -04001128 return fInConditional > 0;
1129
Ethan Nicholase6592142020-09-08 10:22:09 -04001130 case Statement::Kind::kIf: {
John Stilesb92641c2020-08-31 18:09:01 -04001131 ++fInConditional;
1132 bool result = this->INHERITED::visitStatement(stmt);
1133 --fInConditional;
1134 return result;
1135 }
1136
1137 default:
1138 return false;
1139 }
1140 }
1141
1142 int fInConditional = 0;
1143 using INHERITED = ProgramVisitor;
1144 };
1145
1146 return ContainsConditionalBreak{}.visitStatement(stmt);
John Stiles92219b42020-06-15 12:32:24 -04001147}
1148
Ethan Nicholas5005a222018-08-24 13:06:27 -04001149// returns true if this statement definitely executes a break at the current level (we ignore
1150// nested loops and switches, since any breaks inside of them will merely break the loop / switch)
John Stilesb92641c2020-08-31 18:09:01 -04001151static bool contains_unconditional_break(Statement& stmt) {
1152 class ContainsUnconditionalBreak : public ProgramVisitor {
1153 public:
1154 bool visitStatement(const Statement& stmt) override {
Ethan Nicholase6592142020-09-08 10:22:09 -04001155 switch (stmt.kind()) {
1156 case Statement::Kind::kBlock:
John Stilesb92641c2020-08-31 18:09:01 -04001157 return this->INHERITED::visitStatement(stmt);
1158
Ethan Nicholase6592142020-09-08 10:22:09 -04001159 case Statement::Kind::kBreak:
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001160 return true;
John Stilesb92641c2020-08-31 18:09:01 -04001161
1162 default:
1163 return false;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001164 }
John Stilesb92641c2020-08-31 18:09:01 -04001165 }
John Stiles92219b42020-06-15 12:32:24 -04001166
John Stilesb92641c2020-08-31 18:09:01 -04001167 using INHERITED = ProgramVisitor;
1168 };
John Stiles92219b42020-06-15 12:32:24 -04001169
John Stilesb92641c2020-08-31 18:09:01 -04001170 return ContainsUnconditionalBreak{}.visitStatement(stmt);
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001171}
1172
John Stiles92219b42020-06-15 12:32:24 -04001173static void move_all_but_break(std::unique_ptr<Statement>& stmt,
1174 std::vector<std::unique_ptr<Statement>>* target) {
Ethan Nicholase6592142020-09-08 10:22:09 -04001175 switch (stmt->kind()) {
1176 case Statement::Kind::kBlock: {
John Stiles92219b42020-06-15 12:32:24 -04001177 // Recurse into the block.
1178 Block& block = static_cast<Block&>(*stmt);
1179
1180 std::vector<std::unique_ptr<Statement>> blockStmts;
1181 blockStmts.reserve(block.fStatements.size());
1182 for (std::unique_ptr<Statement>& statementInBlock : block.fStatements) {
1183 move_all_but_break(statementInBlock, &blockStmts);
Ethan Nicholas739e1ca2020-06-11 12:16:14 -04001184 }
John Stiles92219b42020-06-15 12:32:24 -04001185
1186 target->push_back(std::make_unique<Block>(block.fOffset, std::move(blockStmts),
1187 block.fSymbols, block.fIsScope));
Ethan Nicholas739e1ca2020-06-11 12:16:14 -04001188 break;
John Stiles92219b42020-06-15 12:32:24 -04001189 }
1190
Ethan Nicholase6592142020-09-08 10:22:09 -04001191 case Statement::Kind::kBreak:
John Stiles92219b42020-06-15 12:32:24 -04001192 // Do not append a break to the target.
1193 break;
1194
Ethan Nicholas739e1ca2020-06-11 12:16:14 -04001195 default:
John Stiles92219b42020-06-15 12:32:24 -04001196 // Append normal statements to the target.
1197 target->push_back(std::move(stmt));
1198 break;
Ethan Nicholas739e1ca2020-06-11 12:16:14 -04001199 }
1200}
1201
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001202// Returns a block containing all of the statements that will be run if the given case matches
1203// (which, owing to the statements being owned by unique_ptrs, means the switch itself will be
1204// broken by this call and must then be discarded).
1205// Returns null (and leaves the switch unmodified) if no such simple reduction is possible, such as
1206// when break statements appear inside conditionals.
John Stiles92219b42020-06-15 12:32:24 -04001207static std::unique_ptr<Statement> block_for_case(SwitchStatement* switchStatement,
1208 SwitchCase* caseToCapture) {
1209 // We have to be careful to not move any of the pointers until after we're sure we're going to
1210 // succeed, so before we make any changes at all, we check the switch-cases to decide on a plan
1211 // of action. First, find the switch-case we are interested in.
1212 auto iter = switchStatement->fCases.begin();
1213 for (; iter != switchStatement->fCases.end(); ++iter) {
1214 if (iter->get() == caseToCapture) {
1215 break;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001216 }
John Stiles92219b42020-06-15 12:32:24 -04001217 }
1218
1219 // Next, walk forward through the rest of the switch. If we find a conditional break, we're
1220 // stuck and can't simplify at all. If we find an unconditional break, we have a range of
1221 // statements that we can use for simplification.
1222 auto startIter = iter;
1223 Statement* unconditionalBreakStmt = nullptr;
1224 for (; iter != switchStatement->fCases.end(); ++iter) {
1225 for (std::unique_ptr<Statement>& stmt : (*iter)->fStatements) {
1226 if (contains_conditional_break(*stmt)) {
1227 // We can't reduce switch-cases to a block when they have conditional breaks.
1228 return nullptr;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001229 }
John Stiles92219b42020-06-15 12:32:24 -04001230
1231 if (contains_unconditional_break(*stmt)) {
1232 // We found an unconditional break. We can use this block, but we need to strip
1233 // out the break statement.
1234 unconditionalBreakStmt = stmt.get();
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001235 break;
1236 }
1237 }
John Stiles92219b42020-06-15 12:32:24 -04001238
1239 if (unconditionalBreakStmt != nullptr) {
1240 break;
1241 }
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001242 }
John Stiles92219b42020-06-15 12:32:24 -04001243
1244 // We fell off the bottom of the switch or encountered a break. We know the range of statements
1245 // that we need to move over, and we know it's safe to do so.
1246 std::vector<std::unique_ptr<Statement>> caseStmts;
1247
1248 // We can move over most of the statements as-is.
1249 while (startIter != iter) {
1250 for (std::unique_ptr<Statement>& stmt : (*startIter)->fStatements) {
1251 caseStmts.push_back(std::move(stmt));
1252 }
1253 ++startIter;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001254 }
John Stiles92219b42020-06-15 12:32:24 -04001255
1256 // If we found an unconditional break at the end, we need to move what we can while avoiding
1257 // that break.
1258 if (unconditionalBreakStmt != nullptr) {
1259 for (std::unique_ptr<Statement>& stmt : (*startIter)->fStatements) {
1260 if (stmt.get() == unconditionalBreakStmt) {
1261 move_all_but_break(stmt, &caseStmts);
1262 unconditionalBreakStmt = nullptr;
1263 break;
1264 }
1265
1266 caseStmts.push_back(std::move(stmt));
1267 }
1268 }
1269
1270 SkASSERT(unconditionalBreakStmt == nullptr); // Verify that we fixed the unconditional break.
1271
1272 // Return our newly-synthesized block.
1273 return std::make_unique<Block>(/*offset=*/-1, std::move(caseStmts), switchStatement->fSymbols);
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001274}
1275
Ethan Nicholascb670962017-04-20 19:31:52 -04001276void Compiler::simplifyStatement(DefinitionMap& definitions,
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001277 BasicBlock& b,
1278 std::vector<BasicBlock::Node>::iterator* iter,
1279 std::unordered_set<const Variable*>* undefinedVariables,
1280 bool* outUpdated,
1281 bool* outNeedsRescan) {
Ethan Nicholascb670962017-04-20 19:31:52 -04001282 Statement* stmt = (*iter)->statement()->get();
Ethan Nicholase6592142020-09-08 10:22:09 -04001283 switch (stmt->kind()) {
1284 case Statement::Kind::kVarDeclaration: {
John Stilesa5a97b42020-08-18 11:19:07 -04001285 const auto& varDecl = stmt->as<VarDeclaration>();
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001286 if (varDecl.fVar->dead() &&
1287 (!varDecl.fValue ||
1288 !varDecl.fValue->hasSideEffects())) {
1289 if (varDecl.fValue) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001290 SkASSERT((*iter)->statement()->get() == stmt);
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001291 if (!b.tryRemoveExpressionBefore(iter, varDecl.fValue.get())) {
1292 *outNeedsRescan = true;
Ethan Nicholascb670962017-04-20 19:31:52 -04001293 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001294 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001295 (*iter)->setStatement(std::unique_ptr<Statement>(new Nop()));
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001296 *outUpdated = true;
Ethan Nicholascb670962017-04-20 19:31:52 -04001297 }
1298 break;
1299 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001300 case Statement::Kind::kIf: {
John Stilesa5a97b42020-08-18 11:19:07 -04001301 IfStatement& i = stmt->as<IfStatement>();
Ethan Nicholase6592142020-09-08 10:22:09 -04001302 if (i.fTest->kind() == Expression::Kind::kBoolLiteral) {
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001303 // constant if, collapse down to a single branch
John Stilesa5a97b42020-08-18 11:19:07 -04001304 if (i.fTest->as<BoolLiteral>().fValue) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001305 SkASSERT(i.fIfTrue);
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001306 (*iter)->setStatement(std::move(i.fIfTrue));
1307 } else {
1308 if (i.fIfFalse) {
1309 (*iter)->setStatement(std::move(i.fIfFalse));
1310 } else {
1311 (*iter)->setStatement(std::unique_ptr<Statement>(new Nop()));
1312 }
1313 }
1314 *outUpdated = true;
1315 *outNeedsRescan = true;
1316 break;
1317 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001318 if (i.fIfFalse && i.fIfFalse->isEmpty()) {
1319 // else block doesn't do anything, remove it
1320 i.fIfFalse.reset();
1321 *outUpdated = true;
1322 *outNeedsRescan = true;
1323 }
1324 if (!i.fIfFalse && i.fIfTrue->isEmpty()) {
1325 // if block doesn't do anything, no else block
1326 if (i.fTest->hasSideEffects()) {
1327 // test has side effects, keep it
1328 (*iter)->setStatement(std::unique_ptr<Statement>(
1329 new ExpressionStatement(std::move(i.fTest))));
1330 } else {
1331 // no if, no else, no test side effects, kill the whole if
1332 // statement
1333 (*iter)->setStatement(std::unique_ptr<Statement>(new Nop()));
1334 }
1335 *outUpdated = true;
1336 *outNeedsRescan = true;
1337 }
1338 break;
1339 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001340 case Statement::Kind::kSwitch: {
John Stilesa5a97b42020-08-18 11:19:07 -04001341 SwitchStatement& s = stmt->as<SwitchStatement>();
Ethan Nicholas34b19c52020-09-14 11:33:47 -04001342 int64_t switchValue;
1343 if (fIRGenerator->getConstantInt(*s.fValue, &switchValue)) {
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001344 // switch is constant, replace it with the case that matches
1345 bool found = false;
1346 SwitchCase* defaultCase = nullptr;
John Stiles9d944232020-08-19 09:56:49 -04001347 for (const std::unique_ptr<SwitchCase>& c : s.fCases) {
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001348 if (!c->fValue) {
1349 defaultCase = c.get();
1350 continue;
1351 }
Ethan Nicholas34b19c52020-09-14 11:33:47 -04001352 int64_t caseValue;
1353 SkAssertResult(fIRGenerator->getConstantInt(*c->fValue, &caseValue));
1354 if (caseValue == switchValue) {
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001355 std::unique_ptr<Statement> newBlock = block_for_case(&s, c.get());
1356 if (newBlock) {
1357 (*iter)->setStatement(std::move(newBlock));
John Stiles9d944232020-08-19 09:56:49 -04001358 found = true;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001359 break;
1360 } else {
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -04001361 if (s.fIsStatic && !(fFlags & kPermitInvalidStaticTests_Flag)) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001362 this->error(s.fOffset,
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001363 "static switch contains non-static conditional break");
1364 s.fIsStatic = false;
1365 }
1366 return; // can't simplify
1367 }
1368 }
1369 }
1370 if (!found) {
1371 // no matching case. use default if it exists, or kill the whole thing
1372 if (defaultCase) {
1373 std::unique_ptr<Statement> newBlock = block_for_case(&s, defaultCase);
1374 if (newBlock) {
1375 (*iter)->setStatement(std::move(newBlock));
1376 } else {
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -04001377 if (s.fIsStatic && !(fFlags & kPermitInvalidStaticTests_Flag)) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001378 this->error(s.fOffset,
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001379 "static switch contains non-static conditional break");
1380 s.fIsStatic = false;
1381 }
1382 return; // can't simplify
1383 }
1384 } else {
1385 (*iter)->setStatement(std::unique_ptr<Statement>(new Nop()));
1386 }
1387 }
1388 *outUpdated = true;
1389 *outNeedsRescan = true;
1390 }
1391 break;
1392 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001393 case Statement::Kind::kExpression: {
John Stilesa5a97b42020-08-18 11:19:07 -04001394 ExpressionStatement& e = stmt->as<ExpressionStatement>();
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001395 SkASSERT((*iter)->statement()->get() == &e);
Ethan Nicholascb670962017-04-20 19:31:52 -04001396 if (!e.fExpression->hasSideEffects()) {
1397 // Expression statement with no side effects, kill it
1398 if (!b.tryRemoveExpressionBefore(iter, e.fExpression.get())) {
1399 *outNeedsRescan = true;
1400 }
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001401 SkASSERT((*iter)->statement()->get() == stmt);
Ethan Nicholascb670962017-04-20 19:31:52 -04001402 (*iter)->setStatement(std::unique_ptr<Statement>(new Nop()));
1403 *outUpdated = true;
1404 }
1405 break;
1406 }
1407 default:
1408 break;
1409 }
1410}
1411
John Stiles0cc193a2020-09-09 09:39:34 -04001412bool Compiler::scanCFG(FunctionDefinition& f) {
1413 bool madeChanges = false;
1414
Ethan Nicholascb670962017-04-20 19:31:52 -04001415 CFG cfg = CFGGenerator().getCFG(f);
1416 this->computeDataFlow(&cfg);
ethannicholas22f939e2016-10-13 13:25:34 -07001417
1418 // check for unreachable code
1419 for (size_t i = 0; i < cfg.fBlocks.size(); i++) {
John Stiles0cc193a2020-09-09 09:39:34 -04001420 const BasicBlock& block = cfg.fBlocks[i];
1421 if (i != cfg.fStart && !block.fEntrances.size() && block.fNodes.size()) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001422 int offset;
John Stiles0cc193a2020-09-09 09:39:34 -04001423 const BasicBlock::Node& node = block.fNodes[0];
1424 switch (node.fKind) {
Ethan Nicholas86a43402017-01-19 13:32:00 -05001425 case BasicBlock::Node::kStatement_Kind:
John Stiles0cc193a2020-09-09 09:39:34 -04001426 offset = (*node.statement())->fOffset;
Ethan Nicholas86a43402017-01-19 13:32:00 -05001427 break;
1428 case BasicBlock::Node::kExpression_Kind:
John Stiles0cc193a2020-09-09 09:39:34 -04001429 offset = (*node.expression())->fOffset;
1430 if ((*node.expression())->is<BoolLiteral>()) {
Ethan Nicholas70728ef2020-05-28 07:09:00 -04001431 // Function inlining can generate do { ... } while(false) loops which always
1432 // break, so the boolean condition is considered unreachable. Since not
1433 // being able to reach a literal is a non-issue in the first place, we
1434 // don't report an error in this case.
1435 continue;
1436 }
Ethan Nicholas86a43402017-01-19 13:32:00 -05001437 break;
1438 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001439 this->error(offset, String("unreachable"));
ethannicholas22f939e2016-10-13 13:25:34 -07001440 }
1441 }
1442 if (fErrorCount) {
John Stiles0cc193a2020-09-09 09:39:34 -04001443 return madeChanges;
ethannicholas22f939e2016-10-13 13:25:34 -07001444 }
1445
Ethan Nicholascb670962017-04-20 19:31:52 -04001446 // check for dead code & undefined variables, perform constant propagation
1447 std::unordered_set<const Variable*> undefinedVariables;
1448 bool updated;
1449 bool needsRescan = false;
1450 do {
1451 if (needsRescan) {
1452 cfg = CFGGenerator().getCFG(f);
1453 this->computeDataFlow(&cfg);
1454 needsRescan = false;
Ethan Nicholas113628d2017-02-02 16:11:39 -05001455 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001456
1457 updated = false;
Ethan Nicholas1de14812020-06-19 15:32:49 -04001458 bool first = true;
Ethan Nicholascb670962017-04-20 19:31:52 -04001459 for (BasicBlock& b : cfg.fBlocks) {
Ethan Nicholas1de14812020-06-19 15:32:49 -04001460 if (!first && b.fEntrances.empty()) {
1461 // Block was reachable before optimization, but has since become unreachable. In
1462 // addition to being dead code, it's broken - since control flow can't reach it, no
1463 // prior variable definitions can reach it, and therefore variables might look to
1464 // have not been properly assigned. Kill it.
Brian Osmandb16c482020-09-09 15:15:06 -04001465
1466 // We need to do this in two steps. For any variable declarations, the node list
1467 // will contain statement nodes for each VarDeclaration, and then a statement for
1468 // the VarDeclarationsStatement. When we replace the VDS with a Nop, we delete the
1469 // storage of the unique_ptr that the VD nodes are pointing to. So we remove those
1470 // from the node list entirely, first.
1471 b.fNodes.erase(
1472 std::remove_if(b.fNodes.begin(), b.fNodes.end(),
1473 [](const BasicBlock::Node& node) {
1474 return node.fKind == BasicBlock::Node::kStatement_Kind &&
1475 (*node.statement())->is<VarDeclaration>();
1476 }),
1477 b.fNodes.end());
1478
1479 // Now replace any remaining statements in the block with Nops.
Ethan Nicholas1de14812020-06-19 15:32:49 -04001480 for (BasicBlock::Node& node : b.fNodes) {
1481 if (node.fKind == BasicBlock::Node::kStatement_Kind &&
John Stiles0cc193a2020-09-09 09:39:34 -04001482 !(*node.statement())->is<Nop>()) {
1483 node.setStatement(std::make_unique<Nop>());
1484 madeChanges = true;
Ethan Nicholas1de14812020-06-19 15:32:49 -04001485 }
1486 }
1487 continue;
1488 }
1489 first = false;
Ethan Nicholascb670962017-04-20 19:31:52 -04001490 DefinitionMap definitions = b.fBefore;
1491
1492 for (auto iter = b.fNodes.begin(); iter != b.fNodes.end() && !needsRescan; ++iter) {
1493 if (iter->fKind == BasicBlock::Node::kExpression_Kind) {
1494 this->simplifyExpression(definitions, b, &iter, &undefinedVariables, &updated,
1495 &needsRescan);
1496 } else {
1497 this->simplifyStatement(definitions, b, &iter, &undefinedVariables, &updated,
John Stiles0cc193a2020-09-09 09:39:34 -04001498 &needsRescan);
Ethan Nicholascb670962017-04-20 19:31:52 -04001499 }
Ethan Nicholas4b330df2017-05-17 10:52:55 -04001500 if (needsRescan) {
1501 break;
1502 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001503 this->addDefinitions(*iter, &definitions);
1504 }
Brian Osman01a3eb42020-09-14 11:32:49 -04001505
1506 if (needsRescan) {
1507 break;
1508 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001509 }
John Stiles0cc193a2020-09-09 09:39:34 -04001510 madeChanges |= updated;
Ethan Nicholascb670962017-04-20 19:31:52 -04001511 } while (updated);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001512 SkASSERT(!needsRescan);
ethannicholas22f939e2016-10-13 13:25:34 -07001513
Ethan Nicholas91a10532017-06-22 11:24:38 -04001514 // verify static ifs & switches, clean up dead variable decls
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001515 for (BasicBlock& b : cfg.fBlocks) {
1516 DefinitionMap definitions = b.fBefore;
1517
Ethan Nicholas91a10532017-06-22 11:24:38 -04001518 for (auto iter = b.fNodes.begin(); iter != b.fNodes.end() && !needsRescan;) {
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001519 if (iter->fKind == BasicBlock::Node::kStatement_Kind) {
1520 const Statement& s = **iter->statement();
Ethan Nicholase6592142020-09-08 10:22:09 -04001521 switch (s.kind()) {
1522 case Statement::Kind::kIf:
John Stilesa5a97b42020-08-18 11:19:07 -04001523 if (s.as<IfStatement>().fIsStatic &&
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -04001524 !(fFlags & kPermitInvalidStaticTests_Flag)) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001525 this->error(s.fOffset, "static if has non-static test");
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001526 }
Ethan Nicholas91a10532017-06-22 11:24:38 -04001527 ++iter;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001528 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001529 case Statement::Kind::kSwitch:
John Stilesa5a97b42020-08-18 11:19:07 -04001530 if (s.as<SwitchStatement>().fIsStatic &&
John Stiles0cc193a2020-09-09 09:39:34 -04001531 !(fFlags & kPermitInvalidStaticTests_Flag)) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001532 this->error(s.fOffset, "static switch has non-static test");
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001533 }
Ethan Nicholas91a10532017-06-22 11:24:38 -04001534 ++iter;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001535 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001536 case Statement::Kind::kVarDeclarations: {
John Stilesa5a97b42020-08-18 11:19:07 -04001537 VarDeclarations& decls = *s.as<VarDeclarationsStatement>().fDeclaration;
John Stiles0cc193a2020-09-09 09:39:34 -04001538 decls.fVars.erase(
1539 std::remove_if(decls.fVars.begin(), decls.fVars.end(),
1540 [&](const std::unique_ptr<Statement>& var) {
1541 bool nop = var->is<Nop>();
1542 madeChanges |= nop;
1543 return nop;
1544 }),
1545 decls.fVars.end());
1546 if (decls.fVars.empty()) {
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001547 iter = b.fNodes.erase(iter);
1548 } else {
1549 ++iter;
1550 }
1551 break;
1552 }
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001553 default:
Ethan Nicholas91a10532017-06-22 11:24:38 -04001554 ++iter;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001555 break;
1556 }
Ethan Nicholas91a10532017-06-22 11:24:38 -04001557 } else {
1558 ++iter;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001559 }
1560 }
1561 }
1562
ethannicholas22f939e2016-10-13 13:25:34 -07001563 // check for missing return
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001564 if (f.fDeclaration.fReturnType != *fContext->fVoid_Type) {
ethannicholas22f939e2016-10-13 13:25:34 -07001565 if (cfg.fBlocks[cfg.fExit].fEntrances.size()) {
Ethan Nicholasdb80f692019-11-22 14:06:12 -05001566 this->error(f.fOffset, String("function '" + String(f.fDeclaration.fName) +
1567 "' can exit without returning a value"));
ethannicholas22f939e2016-10-13 13:25:34 -07001568 }
1569 }
John Stiles0cc193a2020-09-09 09:39:34 -04001570
1571 return madeChanges;
ethannicholas22f939e2016-10-13 13:25:34 -07001572}
1573
Ethan Nicholas91164d12019-05-15 15:29:54 -04001574void Compiler::registerExternalValue(ExternalValue* value) {
1575 fIRGenerator->fRootSymbolTable->addWithoutOwnership(value->fName, value);
1576}
1577
Ethan Nicholasc18bb512020-07-28 14:46:53 -04001578const Symbol* Compiler::takeOwnership(std::unique_ptr<const Symbol> symbol) {
John Stiles3ae071e2020-08-05 15:29:29 -04001579 return fIRGenerator->fRootSymbolTable->takeOwnershipOfSymbol(std::move(symbol));
Ethan Nicholas91164d12019-05-15 15:29:54 -04001580}
1581
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001582std::unique_ptr<Program> Compiler::convertProgram(Program::Kind kind, String text,
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001583 const Program::Settings& settings) {
ethannicholasb3058bd2016-07-01 08:22:01 -07001584 fErrorText = "";
1585 fErrorCount = 0;
John Stiles7b463002020-08-31 17:29:21 -04001586 fInliner.reset(context(), settings);
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001587 std::vector<std::unique_ptr<ProgramElement>>* inherited;
ethannicholasd598f792016-07-25 10:08:54 -07001588 std::vector<std::unique_ptr<ProgramElement>> elements;
ethannicholasb3058bd2016-07-01 08:22:01 -07001589 switch (kind) {
1590 case Program::kVertex_Kind:
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001591 inherited = &fVertexInclude;
1592 fIRGenerator->fSymbolTable = fVertexSymbolTable;
John Stiles810c8cf2020-08-26 19:46:27 -04001593 fIRGenerator->fIntrinsics = fGPUIntrinsics.get();
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001594 fIRGenerator->start(&settings, inherited);
ethannicholasb3058bd2016-07-01 08:22:01 -07001595 break;
1596 case Program::kFragment_Kind:
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001597 inherited = &fFragmentInclude;
1598 fIRGenerator->fSymbolTable = fFragmentSymbolTable;
John Stiles810c8cf2020-08-26 19:46:27 -04001599 fIRGenerator->fIntrinsics = fGPUIntrinsics.get();
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001600 fIRGenerator->start(&settings, inherited);
ethannicholasb3058bd2016-07-01 08:22:01 -07001601 break;
Ethan Nicholas52cad152017-02-16 16:37:32 -05001602 case Program::kGeometry_Kind:
Ethan Nicholasc18bb512020-07-28 14:46:53 -04001603 this->loadGeometryIntrinsics();
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001604 inherited = &fGeometryInclude;
1605 fIRGenerator->fSymbolTable = fGeometrySymbolTable;
John Stiles810c8cf2020-08-26 19:46:27 -04001606 fIRGenerator->fIntrinsics = fGPUIntrinsics.get();
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001607 fIRGenerator->start(&settings, inherited);
Ethan Nicholas52cad152017-02-16 16:37:32 -05001608 break;
Ethan Nicholasb33fa3f2020-08-06 13:00:19 -04001609 case Program::kFragmentProcessor_Kind: {
Brian Osmandd496172020-08-08 08:17:18 -04001610#if !SKSL_STANDALONE
Ethan Nicholasc18bb512020-07-28 14:46:53 -04001611 {
1612 Rehydrator rehydrator(fContext.get(), fGpuSymbolTable, this,
1613 SKSL_INCLUDE_sksl_fp,
1614 SKSL_INCLUDE_sksl_fp_LENGTH);
1615 fFPSymbolTable = rehydrator.symbolTable();
1616 fFPInclude = rehydrator.elements();
1617 }
1618 inherited = &fFPInclude;
1619 fIRGenerator->fSymbolTable = fFPSymbolTable;
John Stiles810c8cf2020-08-26 19:46:27 -04001620 fIRGenerator->fIntrinsics = fGPUIntrinsics.get();
Ethan Nicholasc18bb512020-07-28 14:46:53 -04001621 fIRGenerator->start(&settings, inherited);
1622 break;
1623#else
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001624 inherited = nullptr;
Ethan Nicholas8da1e652019-05-24 11:01:59 -04001625 fIRGenerator->fSymbolTable = fGpuSymbolTable;
Ethan Nicholasb33fa3f2020-08-06 13:00:19 -04001626 fIRGenerator->start(&settings, /*inherited=*/nullptr, /*builtin=*/true);
John Stiles810c8cf2020-08-26 19:46:27 -04001627 fIRGenerator->fIntrinsics = fGPUIntrinsics.get();
Ethan Nicholasb33fa3f2020-08-06 13:00:19 -04001628 std::ifstream in(SKSL_FP_INCLUDE);
1629 std::string stdText{std::istreambuf_iterator<char>(in),
1630 std::istreambuf_iterator<char>()};
1631 if (in.rdstate()) {
1632 printf("error reading %s\n", SKSL_FP_INCLUDE);
1633 abort();
1634 }
1635 const String* source = fGpuSymbolTable->takeOwnershipOfString(
1636 std::make_unique<String>(stdText.c_str()));
1637 fIRGenerator->convertProgram(kind, source->c_str(), source->length(), &elements);
Ethan Nicholasc18bb512020-07-28 14:46:53 -04001638 fIRGenerator->fIsBuiltinCode = false;
Ethan Nicholas762466e2017-06-29 10:03:38 -04001639 break;
Ethan Nicholasc18bb512020-07-28 14:46:53 -04001640#endif
Ethan Nicholasb33fa3f2020-08-06 13:00:19 -04001641 }
Ethan Nicholas8da1e652019-05-24 11:01:59 -04001642 case Program::kPipelineStage_Kind:
Ethan Nicholasc18bb512020-07-28 14:46:53 -04001643 this->loadPipelineIntrinsics();
Ethan Nicholas8da1e652019-05-24 11:01:59 -04001644 inherited = &fPipelineInclude;
1645 fIRGenerator->fSymbolTable = fPipelineSymbolTable;
John Stiles810c8cf2020-08-26 19:46:27 -04001646 fIRGenerator->fIntrinsics = fGPUIntrinsics.get();
Ethan Nicholas8da1e652019-05-24 11:01:59 -04001647 fIRGenerator->start(&settings, inherited);
1648 break;
Ethan Nicholas746035a2019-04-23 13:31:09 -04001649 case Program::kGeneric_Kind:
Ethan Nicholasc18bb512020-07-28 14:46:53 -04001650 this->loadInterpreterIntrinsics();
Ethan Nicholas8da1e652019-05-24 11:01:59 -04001651 inherited = &fInterpreterInclude;
1652 fIRGenerator->fSymbolTable = fInterpreterSymbolTable;
John Stiles810c8cf2020-08-26 19:46:27 -04001653 fIRGenerator->fIntrinsics = fInterpreterIntrinsics.get();
Ethan Nicholas8da1e652019-05-24 11:01:59 -04001654 fIRGenerator->start(&settings, inherited);
Ethan Nicholas0d997662019-04-08 09:46:01 -04001655 break;
ethannicholasb3058bd2016-07-01 08:22:01 -07001656 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001657 std::unique_ptr<String> textPtr(new String(std::move(text)));
1658 fSource = textPtr.get();
Ethan Nicholasc18bb512020-07-28 14:46:53 -04001659 fIRGenerator->convertProgram(kind, textPtr->c_str(), textPtr->size(), &elements);
John Stilesfbd050b2020-08-03 13:21:46 -04001660 auto result = std::make_unique<Program>(kind,
1661 std::move(textPtr),
1662 settings,
1663 fContext,
1664 inherited,
1665 std::move(elements),
1666 fIRGenerator->fSymbolTable,
1667 fIRGenerator->fInputs);
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001668 if (fErrorCount) {
1669 return nullptr;
1670 }
Ethan Nicholas34b19c52020-09-14 11:33:47 -04001671 if (settings.fOptimize && !this->optimize(*result)) {
1672 return nullptr;
1673 }
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001674 return result;
1675}
1676
Ethan Nicholas00543112018-07-31 09:44:36 -04001677bool Compiler::optimize(Program& program) {
1678 SkASSERT(!fErrorCount);
Ethan Nicholas34b19c52020-09-14 11:33:47 -04001679 fIRGenerator->fKind = program.fKind;
1680 fIRGenerator->fSettings = &program.fSettings;
John Stiles7954d6c2020-09-01 10:53:02 -04001681
Ethan Nicholas34b19c52020-09-14 11:33:47 -04001682 while (fErrorCount == 0) {
1683 bool madeChanges = false;
John Stiles7954d6c2020-09-01 10:53:02 -04001684
Ethan Nicholas34b19c52020-09-14 11:33:47 -04001685 // Scan and optimize based on the control-flow graph for each function.
1686 for (ProgramElement& element : program) {
1687 if (element.is<FunctionDefinition>()) {
1688 madeChanges |= this->scanCFG(element.as<FunctionDefinition>());
1689 }
1690 }
1691
1692 // Perform inline-candidate analysis and inline any functions deemed suitable.
John Stilese36079e2020-09-14 19:08:33 -04001693 madeChanges |= fInliner.analyze(program);
Ethan Nicholas34b19c52020-09-14 11:33:47 -04001694
1695 // Remove dead functions. We wait until after analysis so that we still report errors,
1696 // even in unused code.
1697 if (program.fSettings.fRemoveDeadFunctions) {
1698 program.fElements.erase(
1699 std::remove_if(program.fElements.begin(),
1700 program.fElements.end(),
1701 [&](const std::unique_ptr<ProgramElement>& element) {
1702 if (!element->is<FunctionDefinition>()) {
1703 return false;
1704 }
1705 const auto& fn = element->as<FunctionDefinition>();
1706 bool dead = fn.fDeclaration.fCallCount == 0 &&
1707 fn.fDeclaration.fName != "main";
1708 madeChanges |= dead;
1709 return dead;
1710 }),
1711 program.fElements.end());
1712 }
1713
1714 if (program.fKind != Program::kFragmentProcessor_Kind) {
1715 // Remove dead variables.
John Stileseadfc3b2020-09-02 14:12:41 -04001716 for (ProgramElement& element : program) {
Ethan Nicholas34b19c52020-09-14 11:33:47 -04001717 if (!element.is<VarDeclarations>()) {
1718 continue;
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001719 }
Ethan Nicholas34b19c52020-09-14 11:33:47 -04001720 VarDeclarations& vars = element.as<VarDeclarations>();
1721 vars.fVars.erase(
1722 std::remove_if(vars.fVars.begin(), vars.fVars.end(),
1723 [&](const std::unique_ptr<Statement>& stmt) {
1724 bool dead = stmt->as<VarDeclaration>().fVar->dead();
John Stiles73a6bff2020-09-09 13:40:37 -04001725 madeChanges |= dead;
1726 return dead;
1727 }),
Ethan Nicholas34b19c52020-09-14 11:33:47 -04001728 vars.fVars.end());
John Stiles73a6bff2020-09-09 13:40:37 -04001729 }
1730
Ethan Nicholas34b19c52020-09-14 11:33:47 -04001731 // Remove empty variable declarations with no variables left inside of them.
1732 program.fElements.erase(
1733 std::remove_if(program.fElements.begin(), program.fElements.end(),
1734 [&](const std::unique_ptr<ProgramElement>& element) {
1735 if (!element->is<VarDeclarations>()) {
1736 return false;
1737 }
1738 bool dead = element->as<VarDeclarations>().fVars.empty();
1739 madeChanges |= dead;
1740 return dead;
1741 }),
1742 program.fElements.end());
1743 }
John Stiles73a6bff2020-09-09 13:40:37 -04001744
Ethan Nicholas34b19c52020-09-14 11:33:47 -04001745 if (!madeChanges) {
1746 break;
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001747 }
Ethan Nicholas00543112018-07-31 09:44:36 -04001748 }
1749 return fErrorCount == 0;
1750}
1751
Brian Osmanfb32ddf2019-06-18 10:14:20 -04001752#if defined(SKSL_STANDALONE) || SK_SUPPORT_GPU
1753
Ethan Nicholas00543112018-07-31 09:44:36 -04001754bool Compiler::toSPIRV(Program& program, OutputStream& out) {
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001755#ifdef SK_ENABLE_SPIRV_VALIDATION
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001756 StringStream buffer;
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001757 fSource = program.fSource.get();
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001758 SPIRVCodeGenerator cg(fContext.get(), &program, this, &buffer);
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001759 bool result = cg.generateCode();
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001760 fSource = nullptr;
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001761 if (result) {
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001762 spvtools::SpirvTools tools(SPV_ENV_VULKAN_1_0);
Ethan Nicholas762466e2017-06-29 10:03:38 -04001763 const String& data = buffer.str();
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001764 SkASSERT(0 == data.size() % 4);
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001765 auto dumpmsg = [](spv_message_level_t, const char*, const spv_position_t&, const char* m) {
1766 SkDebugf("SPIR-V validation error: %s\n", m);
1767 };
1768 tools.SetMessageConsumer(dumpmsg);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001769 // Verify that the SPIR-V we produced is valid. If this SkASSERT fails, check the logs prior
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001770 // to the failure to see the validation errors.
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001771 SkAssertResult(tools.Validate((const uint32_t*) data.c_str(), data.size() / 4));
Ethan Nicholas762466e2017-06-29 10:03:38 -04001772 out.write(data.c_str(), data.size());
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001773 }
1774#else
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001775 fSource = program.fSource.get();
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001776 SPIRVCodeGenerator cg(fContext.get(), &program, this, &out);
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001777 bool result = cg.generateCode();
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001778 fSource = nullptr;
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001779#endif
Ethan Nicholasce33f102016-12-09 17:22:59 -05001780 return result;
1781}
1782
Ethan Nicholas00543112018-07-31 09:44:36 -04001783bool Compiler::toSPIRV(Program& program, String* out) {
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001784 StringStream buffer;
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001785 bool result = this->toSPIRV(program, buffer);
1786 if (result) {
Ethan Nicholas762466e2017-06-29 10:03:38 -04001787 *out = buffer.str();
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001788 }
1789 return result;
1790}
1791
Ethan Nicholas00543112018-07-31 09:44:36 -04001792bool Compiler::toGLSL(Program& program, OutputStream& out) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001793 fSource = program.fSource.get();
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001794 GLSLCodeGenerator cg(fContext.get(), &program, this, &out);
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001795 bool result = cg.generateCode();
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001796 fSource = nullptr;
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001797 return result;
1798}
1799
Ethan Nicholas00543112018-07-31 09:44:36 -04001800bool Compiler::toGLSL(Program& program, String* out) {
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001801 StringStream buffer;
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001802 bool result = this->toGLSL(program, buffer);
1803 if (result) {
Ethan Nicholas762466e2017-06-29 10:03:38 -04001804 *out = buffer.str();
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001805 }
1806 return result;
1807}
1808
Brian Osmanc0243912020-02-19 15:35:26 -05001809bool Compiler::toHLSL(Program& program, String* out) {
1810 String spirv;
1811 if (!this->toSPIRV(program, &spirv)) {
1812 return false;
1813 }
1814
1815 return SPIRVtoHLSL(spirv, out);
1816}
1817
Ethan Nicholas00543112018-07-31 09:44:36 -04001818bool Compiler::toMetal(Program& program, OutputStream& out) {
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001819 MetalCodeGenerator cg(fContext.get(), &program, this, &out);
Ethan Nicholascc305772017-10-13 16:17:45 -04001820 bool result = cg.generateCode();
Ethan Nicholascc305772017-10-13 16:17:45 -04001821 return result;
1822}
1823
Ethan Nicholas00543112018-07-31 09:44:36 -04001824bool Compiler::toMetal(Program& program, String* out) {
Timothy Liangb8eeb802018-07-23 16:46:16 -04001825 StringStream buffer;
1826 bool result = this->toMetal(program, buffer);
1827 if (result) {
1828 *out = buffer.str();
1829 }
1830 return result;
1831}
1832
Ethan Nicholas2a479a52020-08-18 16:29:45 -04001833#if defined(SKSL_STANDALONE) || defined(GR_TEST_UTILS)
Ethan Nicholas00543112018-07-31 09:44:36 -04001834bool Compiler::toCPP(Program& program, String name, OutputStream& out) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001835 fSource = program.fSource.get();
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001836 CPPCodeGenerator cg(fContext.get(), &program, this, name, &out);
Ethan Nicholas762466e2017-06-29 10:03:38 -04001837 bool result = cg.generateCode();
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001838 fSource = nullptr;
Ethan Nicholas762466e2017-06-29 10:03:38 -04001839 return result;
1840}
1841
Ethan Nicholas00543112018-07-31 09:44:36 -04001842bool Compiler::toH(Program& program, String name, OutputStream& out) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001843 fSource = program.fSource.get();
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001844 HCodeGenerator cg(fContext.get(), &program, this, name, &out);
Ethan Nicholas762466e2017-06-29 10:03:38 -04001845 bool result = cg.generateCode();
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001846 fSource = nullptr;
Ethan Nicholas00543112018-07-31 09:44:36 -04001847 return result;
1848}
Ethan Nicholas2a479a52020-08-18 16:29:45 -04001849#endif // defined(SKSL_STANDALONE) || defined(GR_TEST_UTILS)
Ethan Nicholas00543112018-07-31 09:44:36 -04001850
Ethan Nicholas2a479a52020-08-18 16:29:45 -04001851#endif // defined(SKSL_STANDALONE) || SK_SUPPORT_GPU
Brian Osman2e29ab52019-09-20 12:19:11 -04001852
1853#if !defined(SKSL_STANDALONE) && SK_SUPPORT_GPU
Brian Osmana4b91692020-08-10 14:26:16 -04001854bool Compiler::toPipelineStage(Program& program, PipelineStageArgs* outArgs) {
Ethan Nicholas00543112018-07-31 09:44:36 -04001855 fSource = program.fSource.get();
1856 StringStream buffer;
Brian Osman300fe1d2020-01-23 15:42:43 -05001857 PipelineStageCodeGenerator cg(fContext.get(), &program, this, &buffer, outArgs);
Ethan Nicholas00543112018-07-31 09:44:36 -04001858 bool result = cg.generateCode();
1859 fSource = nullptr;
1860 if (result) {
Brian Osman107c6662019-12-30 15:02:30 -05001861 outArgs->fCode = buffer.str();
Ethan Nicholas00543112018-07-31 09:44:36 -04001862 }
Ethan Nicholas762466e2017-06-29 10:03:38 -04001863 return result;
1864}
Brian Osmanfb32ddf2019-06-18 10:14:20 -04001865#endif
1866
Ethan Nicholas0e9401d2019-03-21 11:05:37 -04001867std::unique_ptr<ByteCode> Compiler::toByteCode(Program& program) {
Mike Klein853d4ed2020-08-20 00:41:00 +00001868#if defined(SK_ENABLE_SKSL_INTERPRETER)
Brian Osman808f0212020-01-21 15:36:47 -05001869 fSource = program.fSource.get();
Ethan Nicholas0e9401d2019-03-21 11:05:37 -04001870 std::unique_ptr<ByteCode> result(new ByteCode());
Brian Osmanb08cc022020-04-02 11:38:40 -04001871 ByteCodeGenerator cg(fContext.get(), &program, this, result.get());
1872 bool success = cg.generateCode();
1873 fSource = nullptr;
1874 if (success) {
Ethan Nicholas0e9401d2019-03-21 11:05:37 -04001875 return result;
1876 }
Mike Klein853d4ed2020-08-20 00:41:00 +00001877#else
1878 ABORT("ByteCode interpreter not enabled");
1879#endif
Ethan Nicholas0e9401d2019-03-21 11:05:37 -04001880 return nullptr;
1881}
1882
Brian Osman401a0092020-09-10 14:47:24 -04001883const char* Compiler::OperatorName(Token::Kind op) {
1884 switch (op) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001885 case Token::Kind::TK_PLUS: return "+";
1886 case Token::Kind::TK_MINUS: return "-";
1887 case Token::Kind::TK_STAR: return "*";
1888 case Token::Kind::TK_SLASH: return "/";
1889 case Token::Kind::TK_PERCENT: return "%";
1890 case Token::Kind::TK_SHL: return "<<";
1891 case Token::Kind::TK_SHR: return ">>";
1892 case Token::Kind::TK_LOGICALNOT: return "!";
1893 case Token::Kind::TK_LOGICALAND: return "&&";
1894 case Token::Kind::TK_LOGICALOR: return "||";
1895 case Token::Kind::TK_LOGICALXOR: return "^^";
1896 case Token::Kind::TK_BITWISENOT: return "~";
1897 case Token::Kind::TK_BITWISEAND: return "&";
1898 case Token::Kind::TK_BITWISEOR: return "|";
1899 case Token::Kind::TK_BITWISEXOR: return "^";
1900 case Token::Kind::TK_EQ: return "=";
1901 case Token::Kind::TK_EQEQ: return "==";
1902 case Token::Kind::TK_NEQ: return "!=";
1903 case Token::Kind::TK_LT: return "<";
1904 case Token::Kind::TK_GT: return ">";
1905 case Token::Kind::TK_LTEQ: return "<=";
1906 case Token::Kind::TK_GTEQ: return ">=";
1907 case Token::Kind::TK_PLUSEQ: return "+=";
1908 case Token::Kind::TK_MINUSEQ: return "-=";
1909 case Token::Kind::TK_STAREQ: return "*=";
1910 case Token::Kind::TK_SLASHEQ: return "/=";
1911 case Token::Kind::TK_PERCENTEQ: return "%=";
1912 case Token::Kind::TK_SHLEQ: return "<<=";
1913 case Token::Kind::TK_SHREQ: return ">>=";
1914 case Token::Kind::TK_LOGICALANDEQ: return "&&=";
1915 case Token::Kind::TK_LOGICALOREQ: return "||=";
1916 case Token::Kind::TK_LOGICALXOREQ: return "^^=";
1917 case Token::Kind::TK_BITWISEANDEQ: return "&=";
1918 case Token::Kind::TK_BITWISEOREQ: return "|=";
1919 case Token::Kind::TK_BITWISEXOREQ: return "^=";
1920 case Token::Kind::TK_PLUSPLUS: return "++";
1921 case Token::Kind::TK_MINUSMINUS: return "--";
1922 case Token::Kind::TK_COMMA: return ",";
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001923 default:
Brian Osman401a0092020-09-10 14:47:24 -04001924 ABORT("unsupported operator: %d\n", (int) op);
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001925 }
1926}
1927
1928
1929bool Compiler::IsAssignment(Token::Kind op) {
1930 switch (op) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001931 case Token::Kind::TK_EQ: // fall through
1932 case Token::Kind::TK_PLUSEQ: // fall through
1933 case Token::Kind::TK_MINUSEQ: // fall through
1934 case Token::Kind::TK_STAREQ: // fall through
1935 case Token::Kind::TK_SLASHEQ: // fall through
1936 case Token::Kind::TK_PERCENTEQ: // fall through
1937 case Token::Kind::TK_SHLEQ: // fall through
1938 case Token::Kind::TK_SHREQ: // fall through
1939 case Token::Kind::TK_BITWISEOREQ: // fall through
1940 case Token::Kind::TK_BITWISEXOREQ: // fall through
1941 case Token::Kind::TK_BITWISEANDEQ: // fall through
1942 case Token::Kind::TK_LOGICALOREQ: // fall through
1943 case Token::Kind::TK_LOGICALXOREQ: // fall through
1944 case Token::Kind::TK_LOGICALANDEQ:
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001945 return true;
1946 default:
1947 return false;
1948 }
1949}
1950
Brian Osman401a0092020-09-10 14:47:24 -04001951Token::Kind Compiler::RemoveAssignment(Token::Kind op) {
1952 switch (op) {
1953 case Token::Kind::TK_PLUSEQ: return Token::Kind::TK_PLUS;
1954 case Token::Kind::TK_MINUSEQ: return Token::Kind::TK_MINUS;
1955 case Token::Kind::TK_STAREQ: return Token::Kind::TK_STAR;
1956 case Token::Kind::TK_SLASHEQ: return Token::Kind::TK_SLASH;
1957 case Token::Kind::TK_PERCENTEQ: return Token::Kind::TK_PERCENT;
1958 case Token::Kind::TK_SHLEQ: return Token::Kind::TK_SHL;
1959 case Token::Kind::TK_SHREQ: return Token::Kind::TK_SHR;
1960 case Token::Kind::TK_BITWISEOREQ: return Token::Kind::TK_BITWISEOR;
1961 case Token::Kind::TK_BITWISEXOREQ: return Token::Kind::TK_BITWISEXOR;
1962 case Token::Kind::TK_BITWISEANDEQ: return Token::Kind::TK_BITWISEAND;
1963 case Token::Kind::TK_LOGICALOREQ: return Token::Kind::TK_LOGICALOR;
1964 case Token::Kind::TK_LOGICALXOREQ: return Token::Kind::TK_LOGICALXOR;
1965 case Token::Kind::TK_LOGICALANDEQ: return Token::Kind::TK_LOGICALAND;
1966 default: return op;
1967 }
1968}
1969
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001970Position Compiler::position(int offset) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001971 SkASSERT(fSource);
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001972 int line = 1;
1973 int column = 1;
1974 for (int i = 0; i < offset; i++) {
1975 if ((*fSource)[i] == '\n') {
1976 ++line;
1977 column = 1;
1978 }
1979 else {
1980 ++column;
1981 }
1982 }
1983 return Position(line, column);
1984}
1985
1986void Compiler::error(int offset, String msg) {
ethannicholasb3058bd2016-07-01 08:22:01 -07001987 fErrorCount++;
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001988 Position pos = this->position(offset);
1989 fErrorText += "error: " + to_string(pos.fLine) + ": " + msg.c_str() + "\n";
ethannicholasb3058bd2016-07-01 08:22:01 -07001990}
1991
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001992String Compiler::errorText() {
Ethan Nicholas00543112018-07-31 09:44:36 -04001993 this->writeErrorCount();
1994 fErrorCount = 0;
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001995 String result = fErrorText;
ethannicholasb3058bd2016-07-01 08:22:01 -07001996 return result;
1997}
1998
1999void Compiler::writeErrorCount() {
2000 if (fErrorCount) {
2001 fErrorText += to_string(fErrorCount) + " error";
2002 if (fErrorCount > 1) {
2003 fErrorText += "s";
2004 }
2005 fErrorText += "\n";
2006 }
2007}
2008
John Stilesa6841be2020-08-06 14:11:56 -04002009} // namespace SkSL