blob: 85702b987072932558f368bca7b4e3b6f8320f53 [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
Mike Kleinc0bd9f92019-04-23 12:05:21 -050013#include "src/sksl/SkSLByteCodeGenerator.h"
14#include "src/sksl/SkSLCFGGenerator.h"
15#include "src/sksl/SkSLCPPCodeGenerator.h"
16#include "src/sksl/SkSLGLSLCodeGenerator.h"
17#include "src/sksl/SkSLHCodeGenerator.h"
18#include "src/sksl/SkSLIRGenerator.h"
19#include "src/sksl/SkSLMetalCodeGenerator.h"
20#include "src/sksl/SkSLPipelineStageCodeGenerator.h"
Ethan Nicholasc18bb512020-07-28 14:46:53 -040021#include "src/sksl/SkSLRehydrator.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050022#include "src/sksl/SkSLSPIRVCodeGenerator.h"
Brian Osmanc0243912020-02-19 15:35:26 -050023#include "src/sksl/SkSLSPIRVtoHLSL.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050024#include "src/sksl/ir/SkSLEnum.h"
25#include "src/sksl/ir/SkSLExpression.h"
26#include "src/sksl/ir/SkSLExpressionStatement.h"
27#include "src/sksl/ir/SkSLFunctionCall.h"
28#include "src/sksl/ir/SkSLIntLiteral.h"
29#include "src/sksl/ir/SkSLModifiersDeclaration.h"
30#include "src/sksl/ir/SkSLNop.h"
31#include "src/sksl/ir/SkSLSymbolTable.h"
32#include "src/sksl/ir/SkSLTernaryExpression.h"
33#include "src/sksl/ir/SkSLUnresolvedFunction.h"
34#include "src/sksl/ir/SkSLVarDeclarations.h"
ethannicholasb3058bd2016-07-01 08:22:01 -070035
Ethan Nicholasb33fa3f2020-08-06 13:00:19 -040036#include <fstream>
37
Ethan Nicholasa11035b2019-11-26 16:27:47 -050038#if !defined(SKSL_STANDALONE) & SK_SUPPORT_GPU
39#include "include/gpu/GrContextOptions.h"
40#include "src/gpu/GrShaderCaps.h"
41#endif
42
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -040043#ifdef SK_ENABLE_SPIRV_VALIDATION
44#include "spirv-tools/libspirv.hpp"
45#endif
46
Brian Osmandd496172020-08-08 08:17:18 -040047#if !SKSL_STANDALONE
Ethan Nicholasc18bb512020-07-28 14:46:53 -040048
49#include "src/sksl/generated/sksl_fp.dehydrated.sksl"
50#include "src/sksl/generated/sksl_frag.dehydrated.sksl"
51#include "src/sksl/generated/sksl_geom.dehydrated.sksl"
52#include "src/sksl/generated/sksl_gpu.dehydrated.sksl"
53#include "src/sksl/generated/sksl_interp.dehydrated.sksl"
54#include "src/sksl/generated/sksl_pipeline.dehydrated.sksl"
55#include "src/sksl/generated/sksl_vert.dehydrated.sksl"
56
57#else
58
Brian Osmandd496172020-08-08 08:17:18 -040059// GN generates or copies all of these files to the skslc executable directory
60static const char SKSL_GPU_INCLUDE[] = "sksl_gpu.sksl";
61static const char SKSL_INTERP_INCLUDE[] = "sksl_interp.sksl";
62static const char SKSL_VERT_INCLUDE[] = "sksl_vert.sksl";
63static const char SKSL_FRAG_INCLUDE[] = "sksl_frag.sksl";
64static const char SKSL_GEOM_INCLUDE[] = "sksl_geom.sksl";
65static const char SKSL_FP_INCLUDE[] = "sksl_fp.sksl";
66static const char SKSL_PIPELINE_INCLUDE[] = "sksl_pipeline.sksl";
Ethan Nicholasc18bb512020-07-28 14:46:53 -040067
68#endif
Ethan Nicholas0d997662019-04-08 09:46:01 -040069
ethannicholasb3058bd2016-07-01 08:22:01 -070070namespace SkSL {
71
Ethan Nicholasdb80f692019-11-22 14:06:12 -050072static void grab_intrinsics(std::vector<std::unique_ptr<ProgramElement>>* src,
John Stiles810c8cf2020-08-26 19:46:27 -040073 IRIntrinsicMap* target) {
Brian Osman08f986d2020-05-13 17:06:46 -040074 for (auto iter = src->begin(); iter != src->end(); ) {
75 std::unique_ptr<ProgramElement>& element = *iter;
Ethan Nicholasdb80f692019-11-22 14:06:12 -050076 switch (element->fKind) {
77 case ProgramElement::kFunction_Kind: {
John Stiles3dc0da62020-08-19 17:48:31 -040078 FunctionDefinition& f = element->as<FunctionDefinition>();
Brian Osman08f986d2020-05-13 17:06:46 -040079 SkASSERT(f.fDeclaration.fBuiltin);
Ethan Nicholasc18bb512020-07-28 14:46:53 -040080 String key = f.fDeclaration.description();
Brian Osman08f986d2020-05-13 17:06:46 -040081 SkASSERT(target->find(key) == target->end());
John Stiles810c8cf2020-08-26 19:46:27 -040082 (*target)[key] = IRIntrinsic{std::move(element), /*fAlreadyIncluded=*/false};
Brian Osman08f986d2020-05-13 17:06:46 -040083 iter = src->erase(iter);
Ethan Nicholasdb80f692019-11-22 14:06:12 -050084 break;
85 }
86 case ProgramElement::kEnum_Kind: {
John Stiles3dc0da62020-08-19 17:48:31 -040087 Enum& e = element->as<Enum>();
Ethan Nicholasdb80f692019-11-22 14:06:12 -050088 StringFragment name = e.fTypeName;
89 SkASSERT(target->find(name) == target->end());
John Stiles810c8cf2020-08-26 19:46:27 -040090 (*target)[name] = IRIntrinsic{std::move(element), /*fAlreadyIncluded=*/false};
Brian Osman08f986d2020-05-13 17:06:46 -040091 iter = src->erase(iter);
Ethan Nicholasdb80f692019-11-22 14:06:12 -050092 break;
93 }
94 default:
95 printf("unsupported include file element\n");
96 SkASSERT(false);
97 }
98 }
99}
100
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -0400101Compiler::Compiler(Flags flags)
John Stiles810c8cf2020-08-26 19:46:27 -0400102: fGPUIntrinsics(std::make_unique<IRIntrinsicMap>())
103, fInterpreterIntrinsics(std::make_unique<IRIntrinsicMap>())
104, fFlags(flags)
105, fContext(std::make_shared<Context>())
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -0400106, fErrorCount(0) {
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400107 auto symbols = std::shared_ptr<SymbolTable>(new SymbolTable(this));
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400108 fIRGenerator = new IRGenerator(fContext.get(), symbols, *this);
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400109 #define ADD_TYPE(t) symbols->addWithoutOwnership(fContext->f ## t ## _Type->fName, \
110 fContext->f ## t ## _Type.get())
ethannicholasb3058bd2016-07-01 08:22:01 -0700111 ADD_TYPE(Void);
112 ADD_TYPE(Float);
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400113 ADD_TYPE(Float2);
114 ADD_TYPE(Float3);
115 ADD_TYPE(Float4);
Ethan Nicholasdcba08e2017-08-02 10:52:54 -0400116 ADD_TYPE(Half);
117 ADD_TYPE(Half2);
118 ADD_TYPE(Half3);
119 ADD_TYPE(Half4);
ethannicholasb3058bd2016-07-01 08:22:01 -0700120 ADD_TYPE(Int);
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400121 ADD_TYPE(Int2);
122 ADD_TYPE(Int3);
123 ADD_TYPE(Int4);
ethannicholasb3058bd2016-07-01 08:22:01 -0700124 ADD_TYPE(UInt);
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400125 ADD_TYPE(UInt2);
126 ADD_TYPE(UInt3);
127 ADD_TYPE(UInt4);
Ethan Nicholasdcba08e2017-08-02 10:52:54 -0400128 ADD_TYPE(Short);
129 ADD_TYPE(Short2);
130 ADD_TYPE(Short3);
131 ADD_TYPE(Short4);
132 ADD_TYPE(UShort);
133 ADD_TYPE(UShort2);
134 ADD_TYPE(UShort3);
135 ADD_TYPE(UShort4);
Ruiqi Maob609e6d2018-07-17 10:19:38 -0400136 ADD_TYPE(Byte);
137 ADD_TYPE(Byte2);
138 ADD_TYPE(Byte3);
139 ADD_TYPE(Byte4);
140 ADD_TYPE(UByte);
141 ADD_TYPE(UByte2);
142 ADD_TYPE(UByte3);
143 ADD_TYPE(UByte4);
ethannicholasb3058bd2016-07-01 08:22:01 -0700144 ADD_TYPE(Bool);
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400145 ADD_TYPE(Bool2);
146 ADD_TYPE(Bool3);
147 ADD_TYPE(Bool4);
148 ADD_TYPE(Float2x2);
149 ADD_TYPE(Float2x3);
150 ADD_TYPE(Float2x4);
151 ADD_TYPE(Float3x2);
152 ADD_TYPE(Float3x3);
153 ADD_TYPE(Float3x4);
154 ADD_TYPE(Float4x2);
155 ADD_TYPE(Float4x3);
156 ADD_TYPE(Float4x4);
Ethan Nicholasdcba08e2017-08-02 10:52:54 -0400157 ADD_TYPE(Half2x2);
158 ADD_TYPE(Half2x3);
159 ADD_TYPE(Half2x4);
160 ADD_TYPE(Half3x2);
161 ADD_TYPE(Half3x3);
162 ADD_TYPE(Half3x4);
163 ADD_TYPE(Half4x2);
164 ADD_TYPE(Half4x3);
165 ADD_TYPE(Half4x4);
ethannicholasb3058bd2016-07-01 08:22:01 -0700166 ADD_TYPE(GenType);
Ethan Nicholasdcba08e2017-08-02 10:52:54 -0400167 ADD_TYPE(GenHType);
ethannicholasb3058bd2016-07-01 08:22:01 -0700168 ADD_TYPE(GenIType);
169 ADD_TYPE(GenUType);
170 ADD_TYPE(GenBType);
171 ADD_TYPE(Mat);
172 ADD_TYPE(Vec);
173 ADD_TYPE(GVec);
174 ADD_TYPE(GVec2);
175 ADD_TYPE(GVec3);
176 ADD_TYPE(GVec4);
Ethan Nicholasdcba08e2017-08-02 10:52:54 -0400177 ADD_TYPE(HVec);
ethannicholasb3058bd2016-07-01 08:22:01 -0700178 ADD_TYPE(IVec);
179 ADD_TYPE(UVec);
Ethan Nicholasdcba08e2017-08-02 10:52:54 -0400180 ADD_TYPE(SVec);
181 ADD_TYPE(USVec);
Ruiqi Maob609e6d2018-07-17 10:19:38 -0400182 ADD_TYPE(ByteVec);
183 ADD_TYPE(UByteVec);
ethannicholasb3058bd2016-07-01 08:22:01 -0700184 ADD_TYPE(BVec);
185
186 ADD_TYPE(Sampler1D);
187 ADD_TYPE(Sampler2D);
188 ADD_TYPE(Sampler3D);
ethannicholas5961bc92016-10-12 06:39:56 -0700189 ADD_TYPE(SamplerExternalOES);
ethannicholasb3058bd2016-07-01 08:22:01 -0700190 ADD_TYPE(SamplerCube);
191 ADD_TYPE(Sampler2DRect);
192 ADD_TYPE(Sampler1DArray);
193 ADD_TYPE(Sampler2DArray);
194 ADD_TYPE(SamplerCubeArray);
195 ADD_TYPE(SamplerBuffer);
196 ADD_TYPE(Sampler2DMS);
197 ADD_TYPE(Sampler2DMSArray);
198
Brian Salomonbf7b6202016-11-11 16:08:03 -0500199 ADD_TYPE(ISampler2D);
200
Brian Salomon2a51de82016-11-16 12:06:01 -0500201 ADD_TYPE(Image2D);
202 ADD_TYPE(IImage2D);
203
Greg Daniel64773e62016-11-22 09:44:03 -0500204 ADD_TYPE(SubpassInput);
205 ADD_TYPE(SubpassInputMS);
206
ethannicholasb3058bd2016-07-01 08:22:01 -0700207 ADD_TYPE(GSampler1D);
208 ADD_TYPE(GSampler2D);
209 ADD_TYPE(GSampler3D);
210 ADD_TYPE(GSamplerCube);
211 ADD_TYPE(GSampler2DRect);
212 ADD_TYPE(GSampler1DArray);
213 ADD_TYPE(GSampler2DArray);
214 ADD_TYPE(GSamplerCubeArray);
215 ADD_TYPE(GSamplerBuffer);
216 ADD_TYPE(GSampler2DMS);
217 ADD_TYPE(GSampler2DMSArray);
218
219 ADD_TYPE(Sampler1DShadow);
220 ADD_TYPE(Sampler2DShadow);
221 ADD_TYPE(SamplerCubeShadow);
222 ADD_TYPE(Sampler2DRectShadow);
223 ADD_TYPE(Sampler1DArrayShadow);
224 ADD_TYPE(Sampler2DArrayShadow);
225 ADD_TYPE(SamplerCubeArrayShadow);
226 ADD_TYPE(GSampler2DArrayShadow);
227 ADD_TYPE(GSamplerCubeArrayShadow);
Ethan Nicholasc9472af2017-10-10 16:30:21 -0400228 ADD_TYPE(FragmentProcessor);
Stephen Whiteff5d7a22019-07-26 17:42:06 -0400229 ADD_TYPE(Sampler);
230 ADD_TYPE(Texture2D);
ethannicholasb3058bd2016-07-01 08:22:01 -0700231
Brian Osman28590d52020-03-23 16:59:08 -0400232 StringFragment fpAliasName("shader");
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400233 symbols->addWithoutOwnership(fpAliasName, fContext->fFragmentProcessor_Type.get());
Brian Osman28590d52020-03-23 16:59:08 -0400234
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700235 StringFragment skCapsName("sk_Caps");
John Stiles311dd9d2020-08-13 17:09:29 -0400236 fIRGenerator->fSymbolTable->add(
237 skCapsName,
238 std::make_unique<Variable>(/*offset=*/-1, Modifiers(), skCapsName,
239 *fContext->fSkCaps_Type, Variable::kGlobal_Storage));
Ethan Nicholas3605ace2016-11-21 15:59:48 -0500240
John Stiles810c8cf2020-08-26 19:46:27 -0400241 fIRGenerator->fIntrinsics = fGPUIntrinsics.get();
Ethan Nicholasdb80f692019-11-22 14:06:12 -0500242 std::vector<std::unique_ptr<ProgramElement>> gpuIntrinsics;
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400243 std::vector<std::unique_ptr<ProgramElement>> interpIntrinsics;
Brian Osmandd496172020-08-08 08:17:18 -0400244#if SKSL_STANDALONE
Ethan Nicholasb33fa3f2020-08-06 13:00:19 -0400245 this->processIncludeFile(Program::kFragment_Kind, SKSL_GPU_INCLUDE, symbols, &gpuIntrinsics,
246 &fGpuSymbolTable);
247 this->processIncludeFile(Program::kVertex_Kind, SKSL_VERT_INCLUDE, fGpuSymbolTable,
248 &fVertexInclude, &fVertexSymbolTable);
249 this->processIncludeFile(Program::kFragment_Kind, SKSL_FRAG_INCLUDE, fGpuSymbolTable,
250 &fFragmentInclude, &fFragmentSymbolTable);
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400251#else
252 {
253 Rehydrator rehydrator(fContext.get(), symbols, this, SKSL_INCLUDE_sksl_gpu,
254 SKSL_INCLUDE_sksl_gpu_LENGTH);
255 fGpuSymbolTable = rehydrator.symbolTable();
256 gpuIntrinsics = rehydrator.elements();
257 }
258 {
259 Rehydrator rehydrator(fContext.get(), fGpuSymbolTable, this, SKSL_INCLUDE_sksl_vert,
260 SKSL_INCLUDE_sksl_vert_LENGTH);
261 fVertexSymbolTable = rehydrator.symbolTable();
262 fVertexInclude = rehydrator.elements();
263 }
264 {
265 Rehydrator rehydrator(fContext.get(), fGpuSymbolTable, this, SKSL_INCLUDE_sksl_frag,
266 SKSL_INCLUDE_sksl_frag_LENGTH);
267 fFragmentSymbolTable = rehydrator.symbolTable();
268 fFragmentInclude = rehydrator.elements();
269 }
270#endif
John Stiles810c8cf2020-08-26 19:46:27 -0400271 grab_intrinsics(&gpuIntrinsics, fGPUIntrinsics.get());
272 grab_intrinsics(&interpIntrinsics, fInterpreterIntrinsics.get());
ethannicholasb3058bd2016-07-01 08:22:01 -0700273}
274
275Compiler::~Compiler() {
276 delete fIRGenerator;
277}
278
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400279void Compiler::loadGeometryIntrinsics() {
280 if (fGeometrySymbolTable) {
281 return;
282 }
Brian Osmandd496172020-08-08 08:17:18 -0400283 #if !SKSL_STANDALONE
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400284 {
285 Rehydrator rehydrator(fContext.get(), fGpuSymbolTable, this, SKSL_INCLUDE_sksl_geom,
286 SKSL_INCLUDE_sksl_geom_LENGTH);
287 fGeometrySymbolTable = rehydrator.symbolTable();
288 fGeometryInclude = rehydrator.elements();
289 }
290 #else
Ethan Nicholasb33fa3f2020-08-06 13:00:19 -0400291 this->processIncludeFile(Program::kGeometry_Kind, SKSL_GEOM_INCLUDE, fGpuSymbolTable,
292 &fGeometryInclude, &fGeometrySymbolTable);
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400293 #endif
294}
295
296void Compiler::loadPipelineIntrinsics() {
297 if (fPipelineSymbolTable) {
298 return;
299 }
Brian Osmandd496172020-08-08 08:17:18 -0400300 #if !SKSL_STANDALONE
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400301 {
302 Rehydrator rehydrator(fContext.get(), fGpuSymbolTable, this,
303 SKSL_INCLUDE_sksl_pipeline,
304 SKSL_INCLUDE_sksl_pipeline_LENGTH);
305 fPipelineSymbolTable = rehydrator.symbolTable();
306 fPipelineInclude = rehydrator.elements();
307 }
308 #else
309 this->processIncludeFile(Program::kPipelineStage_Kind, SKSL_PIPELINE_INCLUDE,
Ethan Nicholasb33fa3f2020-08-06 13:00:19 -0400310 fGpuSymbolTable, &fPipelineInclude, &fPipelineSymbolTable);
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400311 #endif
312}
313
314void Compiler::loadInterpreterIntrinsics() {
315 if (fInterpreterSymbolTable) {
316 return;
317 }
318 this->loadPipelineIntrinsics();
Brian Osmandd496172020-08-08 08:17:18 -0400319 #if !SKSL_STANDALONE
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400320 {
321 Rehydrator rehydrator(fContext.get(), fPipelineSymbolTable, this,
322 SKSL_INCLUDE_sksl_interp,
323 SKSL_INCLUDE_sksl_interp_LENGTH);
324 fInterpreterSymbolTable = rehydrator.symbolTable();
325 fInterpreterInclude = rehydrator.elements();
326 }
327 #else
328 this->processIncludeFile(Program::kGeneric_Kind, SKSL_INTERP_INCLUDE,
Ethan Nicholasb33fa3f2020-08-06 13:00:19 -0400329 fIRGenerator->fSymbolTable, &fInterpreterInclude,
330 &fInterpreterSymbolTable);
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400331 #endif
332}
333
Ethan Nicholasb33fa3f2020-08-06 13:00:19 -0400334void Compiler::processIncludeFile(Program::Kind kind, const char* path,
Ethan Nicholas8da1e652019-05-24 11:01:59 -0400335 std::shared_ptr<SymbolTable> base,
336 std::vector<std::unique_ptr<ProgramElement>>* outElements,
337 std::shared_ptr<SymbolTable>* outSymbolTable) {
Ethan Nicholasb33fa3f2020-08-06 13:00:19 -0400338 std::ifstream in(path);
339 std::string stdText{std::istreambuf_iterator<char>(in),
340 std::istreambuf_iterator<char>()};
341 if (in.rdstate()) {
342 printf("error reading %s\n", path);
343 abort();
344 }
345 if (!base) {
346 base = fIRGenerator->fSymbolTable;
347 }
348 SkASSERT(base);
349 const String* source = base->takeOwnershipOfString(std::make_unique<String>(stdText.c_str()));
350 fSource = source;
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400351 std::shared_ptr<SymbolTable> old = fIRGenerator->fSymbolTable;
352 if (base) {
353 fIRGenerator->fSymbolTable = std::move(base);
354 }
Ethan Nicholas8da1e652019-05-24 11:01:59 -0400355 Program::Settings settings;
Ethan Nicholasa11035b2019-11-26 16:27:47 -0500356#if !defined(SKSL_STANDALONE) & SK_SUPPORT_GPU
357 GrContextOptions opts;
358 GrShaderCaps caps(opts);
359 settings.fCaps = &caps;
360#endif
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400361 SkASSERT(fIRGenerator->fCanInline);
362 fIRGenerator->fCanInline = false;
363 fIRGenerator->start(&settings, nullptr, true);
Ethan Nicholasb33fa3f2020-08-06 13:00:19 -0400364 fIRGenerator->convertProgram(kind, source->c_str(), source->length(), outElements);
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400365 fIRGenerator->fCanInline = true;
Ethan Nicholas8da1e652019-05-24 11:01:59 -0400366 if (this->fErrorCount) {
367 printf("Unexpected errors: %s\n", this->fErrorText.c_str());
368 }
369 SkASSERT(!fErrorCount);
Ethan Nicholas8da1e652019-05-24 11:01:59 -0400370 *outSymbolTable = fIRGenerator->fSymbolTable;
Ethan Nicholasa11035b2019-11-26 16:27:47 -0500371#ifdef SK_DEBUG
372 fSource = nullptr;
373#endif
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400374 fIRGenerator->fSymbolTable = std::move(old);
Ethan Nicholas8da1e652019-05-24 11:01:59 -0400375}
376
ethannicholas22f939e2016-10-13 13:25:34 -0700377// add the definition created by assigning to the lvalue to the definition set
Ethan Nicholas86a43402017-01-19 13:32:00 -0500378void Compiler::addDefinition(const Expression* lvalue, std::unique_ptr<Expression>* expr,
379 DefinitionMap* definitions) {
ethannicholas22f939e2016-10-13 13:25:34 -0700380 switch (lvalue->fKind) {
381 case Expression::kVariableReference_Kind: {
John Stilesa5a97b42020-08-18 11:19:07 -0400382 const Variable& var = lvalue->as<VariableReference>().fVariable;
ethannicholas22f939e2016-10-13 13:25:34 -0700383 if (var.fStorage == Variable::kLocal_Storage) {
384 (*definitions)[&var] = expr;
385 }
386 break;
387 }
388 case Expression::kSwizzle_Kind:
389 // We consider the variable written to as long as at least some of its components have
390 // been written to. This will lead to some false negatives (we won't catch it if you
391 // write to foo.x and then read foo.y), but being stricter could lead to false positives
Mike Klein6ad99092016-10-26 10:35:22 -0400392 // (we write to foo.x, and then pass foo to a function which happens to only read foo.x,
393 // 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 -0700394 // more complicated whole-program analysis. This is probably good enough.
John Stilesa5a97b42020-08-18 11:19:07 -0400395 this->addDefinition(lvalue->as<Swizzle>().fBase.get(),
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400396 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
ethannicholas22f939e2016-10-13 13:25:34 -0700397 definitions);
398 break;
399 case Expression::kIndex_Kind:
400 // see comments in Swizzle
John Stilesa5a97b42020-08-18 11:19:07 -0400401 this->addDefinition(lvalue->as<IndexExpression>().fBase.get(),
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400402 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
ethannicholas22f939e2016-10-13 13:25:34 -0700403 definitions);
404 break;
405 case Expression::kFieldAccess_Kind:
406 // see comments in Swizzle
John Stilesa5a97b42020-08-18 11:19:07 -0400407 this->addDefinition(lvalue->as<FieldAccess>().fBase.get(),
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400408 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
ethannicholas22f939e2016-10-13 13:25:34 -0700409 definitions);
410 break;
Ethan Nicholasa583b812018-01-18 13:32:11 -0500411 case Expression::kTernary_Kind:
412 // To simplify analysis, we just pretend that we write to both sides of the ternary.
413 // This allows for false positives (meaning we fail to detect that a variable might not
414 // have been assigned), but is preferable to false negatives.
John Stilesa5a97b42020-08-18 11:19:07 -0400415 this->addDefinition(lvalue->as<TernaryExpression>().fIfTrue.get(),
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400416 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
Ethan Nicholasa583b812018-01-18 13:32:11 -0500417 definitions);
John Stilesa5a97b42020-08-18 11:19:07 -0400418 this->addDefinition(lvalue->as<TernaryExpression>().fIfFalse.get(),
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400419 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
Ethan Nicholasa583b812018-01-18 13:32:11 -0500420 definitions);
421 break;
Ethan Nicholas91164d12019-05-15 15:29:54 -0400422 case Expression::kExternalValue_Kind:
423 break;
ethannicholas22f939e2016-10-13 13:25:34 -0700424 default:
425 // not an lvalue, can't happen
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400426 SkASSERT(false);
ethannicholas22f939e2016-10-13 13:25:34 -0700427 }
428}
429
430// add local variables defined by this node to the set
Mike Klein6ad99092016-10-26 10:35:22 -0400431void Compiler::addDefinitions(const BasicBlock::Node& node,
Ethan Nicholas86a43402017-01-19 13:32:00 -0500432 DefinitionMap* definitions) {
ethannicholas22f939e2016-10-13 13:25:34 -0700433 switch (node.fKind) {
434 case BasicBlock::Node::kExpression_Kind: {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400435 SkASSERT(node.expression());
John Stilesa5a97b42020-08-18 11:19:07 -0400436 Expression* expr = node.expression()->get();
Ethan Nicholas86a43402017-01-19 13:32:00 -0500437 switch (expr->fKind) {
438 case Expression::kBinary_Kind: {
John Stilesa5a97b42020-08-18 11:19:07 -0400439 BinaryExpression* b = &expr->as<BinaryExpression>();
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400440 if (b->fOperator == Token::Kind::TK_EQ) {
Ethan Nicholas86a43402017-01-19 13:32:00 -0500441 this->addDefinition(b->fLeft.get(), &b->fRight, definitions);
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700442 } else if (Compiler::IsAssignment(b->fOperator)) {
Ethan Nicholas86a43402017-01-19 13:32:00 -0500443 this->addDefinition(
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400444 b->fLeft.get(),
445 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
446 definitions);
Ethan Nicholas86a43402017-01-19 13:32:00 -0500447
448 }
449 break;
ethannicholas22f939e2016-10-13 13:25:34 -0700450 }
Ethan Nicholasc6a19f12018-03-29 16:46:56 -0400451 case Expression::kFunctionCall_Kind: {
John Stilesa5a97b42020-08-18 11:19:07 -0400452 const FunctionCall& c = expr->as<FunctionCall>();
Ethan Nicholasc6a19f12018-03-29 16:46:56 -0400453 for (size_t i = 0; i < c.fFunction.fParameters.size(); ++i) {
454 if (c.fFunction.fParameters[i]->fModifiers.fFlags & Modifiers::kOut_Flag) {
455 this->addDefinition(
456 c.fArguments[i].get(),
457 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
458 definitions);
459 }
460 }
461 break;
462 }
Ethan Nicholas86a43402017-01-19 13:32:00 -0500463 case Expression::kPrefix_Kind: {
John Stilesa5a97b42020-08-18 11:19:07 -0400464 const PrefixExpression* p = &expr->as<PrefixExpression>();
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400465 if (p->fOperator == Token::Kind::TK_MINUSMINUS ||
466 p->fOperator == Token::Kind::TK_PLUSPLUS) {
Ethan Nicholas86a43402017-01-19 13:32:00 -0500467 this->addDefinition(
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400468 p->fOperand.get(),
469 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
470 definitions);
Ethan Nicholas86a43402017-01-19 13:32:00 -0500471 }
472 break;
473 }
474 case Expression::kPostfix_Kind: {
John Stilesa5a97b42020-08-18 11:19:07 -0400475 const PostfixExpression* p = &expr->as<PostfixExpression>();
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400476 if (p->fOperator == Token::Kind::TK_MINUSMINUS ||
477 p->fOperator == Token::Kind::TK_PLUSPLUS) {
Ethan Nicholas86a43402017-01-19 13:32:00 -0500478 this->addDefinition(
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400479 p->fOperand.get(),
480 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
481 definitions);
Ethan Nicholas86a43402017-01-19 13:32:00 -0500482 }
483 break;
484 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400485 case Expression::kVariableReference_Kind: {
John Stilesa5a97b42020-08-18 11:19:07 -0400486 const VariableReference* v = &expr->as<VariableReference>();
Ethan Nicholascb670962017-04-20 19:31:52 -0400487 if (v->fRefKind != VariableReference::kRead_RefKind) {
488 this->addDefinition(
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400489 v,
490 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
491 definitions);
Ethan Nicholascb670962017-04-20 19:31:52 -0400492 }
John Stiles30212b72020-06-11 17:55:07 -0400493 break;
Ethan Nicholascb670962017-04-20 19:31:52 -0400494 }
Ethan Nicholas86a43402017-01-19 13:32:00 -0500495 default:
496 break;
ethannicholas22f939e2016-10-13 13:25:34 -0700497 }
498 break;
499 }
500 case BasicBlock::Node::kStatement_Kind: {
John Stilesa5a97b42020-08-18 11:19:07 -0400501 Statement* stmt = node.statement()->get();
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000502 if (stmt->fKind == Statement::kVarDeclaration_Kind) {
John Stilesa5a97b42020-08-18 11:19:07 -0400503 VarDeclaration& vd = stmt->as<VarDeclaration>();
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000504 if (vd.fValue) {
505 (*definitions)[vd.fVar] = &vd.fValue;
ethannicholas22f939e2016-10-13 13:25:34 -0700506 }
507 }
508 break;
509 }
510 }
511}
512
513void Compiler::scanCFG(CFG* cfg, BlockId blockId, std::set<BlockId>* workList) {
514 BasicBlock& block = cfg->fBlocks[blockId];
515
516 // compute definitions after this block
Ethan Nicholas86a43402017-01-19 13:32:00 -0500517 DefinitionMap after = block.fBefore;
ethannicholas22f939e2016-10-13 13:25:34 -0700518 for (const BasicBlock::Node& n : block.fNodes) {
519 this->addDefinitions(n, &after);
520 }
521
522 // propagate definitions to exits
523 for (BlockId exitId : block.fExits) {
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400524 if (exitId == blockId) {
525 continue;
526 }
ethannicholas22f939e2016-10-13 13:25:34 -0700527 BasicBlock& exit = cfg->fBlocks[exitId];
528 for (const auto& pair : after) {
Ethan Nicholas86a43402017-01-19 13:32:00 -0500529 std::unique_ptr<Expression>* e1 = pair.second;
530 auto found = exit.fBefore.find(pair.first);
531 if (found == exit.fBefore.end()) {
532 // exit has no definition for it, just copy it
533 workList->insert(exitId);
ethannicholas22f939e2016-10-13 13:25:34 -0700534 exit.fBefore[pair.first] = e1;
535 } else {
Ethan Nicholas86a43402017-01-19 13:32:00 -0500536 // exit has a (possibly different) value already defined
537 std::unique_ptr<Expression>* e2 = exit.fBefore[pair.first];
ethannicholas22f939e2016-10-13 13:25:34 -0700538 if (e1 != e2) {
539 // definition has changed, merge and add exit block to worklist
540 workList->insert(exitId);
Ethan Nicholasaf197692017-02-27 13:26:45 -0500541 if (e1 && e2) {
542 exit.fBefore[pair.first] =
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400543 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression;
Ethan Nicholasaf197692017-02-27 13:26:45 -0500544 } else {
545 exit.fBefore[pair.first] = nullptr;
546 }
ethannicholas22f939e2016-10-13 13:25:34 -0700547 }
548 }
549 }
550 }
551}
552
553// returns a map which maps all local variables in the function to null, indicating that their value
554// is initially unknown
Ethan Nicholas86a43402017-01-19 13:32:00 -0500555static DefinitionMap compute_start_state(const CFG& cfg) {
556 DefinitionMap result;
Mike Klein6ad99092016-10-26 10:35:22 -0400557 for (const auto& block : cfg.fBlocks) {
558 for (const auto& node : block.fNodes) {
ethannicholas22f939e2016-10-13 13:25:34 -0700559 if (node.fKind == BasicBlock::Node::kStatement_Kind) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400560 SkASSERT(node.statement());
Ethan Nicholascb670962017-04-20 19:31:52 -0400561 const Statement* s = node.statement()->get();
ethannicholas22f939e2016-10-13 13:25:34 -0700562 if (s->fKind == Statement::kVarDeclarations_Kind) {
John Stilesa5a97b42020-08-18 11:19:07 -0400563 const VarDeclarationsStatement* vd = &s->as<VarDeclarationsStatement>();
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000564 for (const auto& decl : vd->fDeclaration->fVars) {
565 if (decl->fKind == Statement::kVarDeclaration_Kind) {
John Stilesa5a97b42020-08-18 11:19:07 -0400566 result[decl->as<VarDeclaration>().fVar] = nullptr;
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000567 }
Mike Klein6ad99092016-10-26 10:35:22 -0400568 }
ethannicholas22f939e2016-10-13 13:25:34 -0700569 }
570 }
571 }
572 }
573 return result;
574}
575
Ethan Nicholascb670962017-04-20 19:31:52 -0400576/**
577 * Returns true if assigning to this lvalue has no effect.
578 */
579static bool is_dead(const Expression& lvalue) {
580 switch (lvalue.fKind) {
581 case Expression::kVariableReference_Kind:
John Stilesa5a97b42020-08-18 11:19:07 -0400582 return lvalue.as<VariableReference>().fVariable.dead();
Ethan Nicholascb670962017-04-20 19:31:52 -0400583 case Expression::kSwizzle_Kind:
John Stilesa5a97b42020-08-18 11:19:07 -0400584 return is_dead(*lvalue.as<Swizzle>().fBase);
Ethan Nicholascb670962017-04-20 19:31:52 -0400585 case Expression::kFieldAccess_Kind:
John Stilesa5a97b42020-08-18 11:19:07 -0400586 return is_dead(*lvalue.as<FieldAccess>().fBase);
Ethan Nicholascb670962017-04-20 19:31:52 -0400587 case Expression::kIndex_Kind: {
John Stilesa5a97b42020-08-18 11:19:07 -0400588 const IndexExpression& idx = lvalue.as<IndexExpression>();
Ethan Nicholas2a099da2020-01-02 14:40:54 -0500589 return is_dead(*idx.fBase) &&
590 !idx.fIndex->hasProperty(Expression::Property::kSideEffects);
Ethan Nicholascb670962017-04-20 19:31:52 -0400591 }
Ethan Nicholasa583b812018-01-18 13:32:11 -0500592 case Expression::kTernary_Kind: {
John Stilesa5a97b42020-08-18 11:19:07 -0400593 const TernaryExpression& t = lvalue.as<TernaryExpression>();
Ethan Nicholasa583b812018-01-18 13:32:11 -0500594 return !t.fTest->hasSideEffects() && is_dead(*t.fIfTrue) && is_dead(*t.fIfFalse);
595 }
Ethan Nicholas91164d12019-05-15 15:29:54 -0400596 case Expression::kExternalValue_Kind:
597 return false;
Ethan Nicholascb670962017-04-20 19:31:52 -0400598 default:
Ethan Nicholas2a099da2020-01-02 14:40:54 -0500599#ifdef SK_DEBUG
Ethan Nicholascb670962017-04-20 19:31:52 -0400600 ABORT("invalid lvalue: %s\n", lvalue.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -0500601#endif
602 return false;
Ethan Nicholascb670962017-04-20 19:31:52 -0400603 }
604}
ethannicholas22f939e2016-10-13 13:25:34 -0700605
Ethan Nicholascb670962017-04-20 19:31:52 -0400606/**
607 * Returns true if this is an assignment which can be collapsed down to just the right hand side due
608 * to a dead target and lack of side effects on the left hand side.
609 */
610static bool dead_assignment(const BinaryExpression& b) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700611 if (!Compiler::IsAssignment(b.fOperator)) {
Ethan Nicholascb670962017-04-20 19:31:52 -0400612 return false;
613 }
614 return is_dead(*b.fLeft);
615}
616
617void Compiler::computeDataFlow(CFG* cfg) {
618 cfg->fBlocks[cfg->fStart].fBefore = compute_start_state(*cfg);
ethannicholas22f939e2016-10-13 13:25:34 -0700619 std::set<BlockId> workList;
Ethan Nicholascb670962017-04-20 19:31:52 -0400620 for (BlockId i = 0; i < cfg->fBlocks.size(); i++) {
ethannicholas22f939e2016-10-13 13:25:34 -0700621 workList.insert(i);
622 }
623 while (workList.size()) {
624 BlockId next = *workList.begin();
625 workList.erase(workList.begin());
Ethan Nicholascb670962017-04-20 19:31:52 -0400626 this->scanCFG(cfg, next, &workList);
ethannicholas22f939e2016-10-13 13:25:34 -0700627 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400628}
629
630/**
631 * Attempts to replace the expression pointed to by iter with a new one (in both the CFG and the
632 * IR). If the expression can be cleanly removed, returns true and updates the iterator to point to
633 * the newly-inserted element. Otherwise updates only the IR and returns false (and the CFG will
634 * need to be regenerated).
635 */
John Stilesafbf8992020-08-18 10:08:21 -0400636static bool try_replace_expression(BasicBlock* b,
637 std::vector<BasicBlock::Node>::iterator* iter,
638 std::unique_ptr<Expression>* newExpression) {
Ethan Nicholascb670962017-04-20 19:31:52 -0400639 std::unique_ptr<Expression>* target = (*iter)->expression();
640 if (!b->tryRemoveExpression(iter)) {
641 *target = std::move(*newExpression);
642 return false;
643 }
644 *target = std::move(*newExpression);
645 return b->tryInsertExpression(iter, target);
646}
647
648/**
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400649 * Returns true if the expression is a constant numeric literal with the specified value, or a
650 * constant vector with all elements equal to the specified value.
Ethan Nicholascb670962017-04-20 19:31:52 -0400651 */
John Stiles9d944232020-08-19 09:56:49 -0400652template <typename T = double>
653static bool is_constant(const Expression& expr, T value) {
Ethan Nicholascb670962017-04-20 19:31:52 -0400654 switch (expr.fKind) {
655 case Expression::kIntLiteral_Kind:
John Stiles81365af2020-08-18 09:24:00 -0400656 return expr.as<IntLiteral>().fValue == value;
John Stiles9d944232020-08-19 09:56:49 -0400657
Ethan Nicholascb670962017-04-20 19:31:52 -0400658 case Expression::kFloatLiteral_Kind:
John Stiles81365af2020-08-18 09:24:00 -0400659 return expr.as<FloatLiteral>().fValue == value;
John Stiles9d944232020-08-19 09:56:49 -0400660
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400661 case Expression::kConstructor_Kind: {
John Stiles9d944232020-08-19 09:56:49 -0400662 const Constructor& constructor = expr.as<Constructor>();
663 if (constructor.isCompileTimeConstant()) {
664 bool isFloat = constructor.fType.columns() > 1
665 ? constructor.fType.componentType().isFloat()
666 : constructor.fType.isFloat();
667 switch (constructor.fType.kind()) {
668 case Type::kVector_Kind:
669 for (int i = 0; i < constructor.fType.columns(); ++i) {
670 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
682 case Type::kScalar_Kind:
683 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 Nicholasd9d33c32018-06-12 11:05:59 -0400708 SkASSERT(!bin.fLeft->hasSideEffects());
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400709 bool result;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400710 if (bin.fOperator == Token::Kind::TK_EQ) {
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400711 result = b->tryRemoveLValueBefore(iter, bin.fLeft.get());
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400712 } else {
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400713 result = b->tryRemoveExpressionBefore(iter, bin.fLeft.get());
Ethan Nicholascb670962017-04-20 19:31:52 -0400714 }
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400715 *target = std::move(bin.fRight);
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400716 if (!result) {
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400717 *outNeedsRescan = true;
718 return;
719 }
720 if (*iter == b->fNodes.begin()) {
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400721 *outNeedsRescan = true;
722 return;
723 }
724 --(*iter);
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400725 if ((*iter)->fKind != BasicBlock::Node::kExpression_Kind ||
726 (*iter)->expression() != &bin.fRight) {
727 *outNeedsRescan = true;
728 return;
729 }
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400730 *iter = b->fNodes.erase(*iter);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400731 SkASSERT((*iter)->expression() == target);
Ethan Nicholascb670962017-04-20 19:31:52 -0400732}
733
734/**
735 * Collapses the binary expression pointed to by iter down to just the left side (in both the IR and
736 * CFG structures).
737 */
John Stilesafbf8992020-08-18 10:08:21 -0400738static void delete_right(BasicBlock* b,
739 std::vector<BasicBlock::Node>::iterator* iter,
740 bool* outUpdated,
741 bool* outNeedsRescan) {
Ethan Nicholascb670962017-04-20 19:31:52 -0400742 *outUpdated = true;
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400743 std::unique_ptr<Expression>* target = (*iter)->expression();
John Stilesa5a97b42020-08-18 11:19:07 -0400744 BinaryExpression& bin = (*target)->as<BinaryExpression>();
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400745 SkASSERT(!bin.fRight->hasSideEffects());
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400746 if (!b->tryRemoveExpressionBefore(iter, bin.fRight.get())) {
747 *target = std::move(bin.fLeft);
Ethan Nicholascb670962017-04-20 19:31:52 -0400748 *outNeedsRescan = true;
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400749 return;
Ethan Nicholascb670962017-04-20 19:31:52 -0400750 }
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400751 *target = std::move(bin.fLeft);
752 if (*iter == b->fNodes.begin()) {
753 *outNeedsRescan = true;
754 return;
755 }
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400756 --(*iter);
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400757 if (((*iter)->fKind != BasicBlock::Node::kExpression_Kind ||
758 (*iter)->expression() != &bin.fLeft)) {
759 *outNeedsRescan = true;
760 return;
761 }
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400762 *iter = b->fNodes.erase(*iter);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400763 SkASSERT((*iter)->expression() == target);
Ethan Nicholascb670962017-04-20 19:31:52 -0400764}
765
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400766/**
767 * Constructs the specified type using a single argument.
768 */
769static std::unique_ptr<Expression> construct(const Type& type, std::unique_ptr<Expression> v) {
770 std::vector<std::unique_ptr<Expression>> args;
771 args.push_back(std::move(v));
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700772 auto result = std::unique_ptr<Expression>(new Constructor(-1, type, std::move(args)));
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400773 return result;
774}
775
776/**
777 * Used in the implementations of vectorize_left and vectorize_right. Given a vector type and an
778 * expression x, deletes the expression pointed to by iter and replaces it with <type>(x).
779 */
780static void vectorize(BasicBlock* b,
781 std::vector<BasicBlock::Node>::iterator* iter,
782 const Type& type,
783 std::unique_ptr<Expression>* otherExpression,
784 bool* outUpdated,
785 bool* outNeedsRescan) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400786 SkASSERT((*(*iter)->expression())->fKind == Expression::kBinary_Kind);
787 SkASSERT(type.kind() == Type::kVector_Kind);
788 SkASSERT((*otherExpression)->fType.kind() == Type::kScalar_Kind);
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400789 *outUpdated = true;
790 std::unique_ptr<Expression>* target = (*iter)->expression();
791 if (!b->tryRemoveExpression(iter)) {
792 *target = construct(type, std::move(*otherExpression));
793 *outNeedsRescan = true;
794 } else {
795 *target = construct(type, std::move(*otherExpression));
796 if (!b->tryInsertExpression(iter, target)) {
797 *outNeedsRescan = true;
798 }
799 }
800}
801
802/**
803 * Given a binary expression of the form x <op> vec<n>(y), deletes the right side and vectorizes the
804 * left to yield vec<n>(x).
805 */
806static void vectorize_left(BasicBlock* b,
807 std::vector<BasicBlock::Node>::iterator* iter,
808 bool* outUpdated,
809 bool* outNeedsRescan) {
John Stilesa5a97b42020-08-18 11:19:07 -0400810 BinaryExpression& bin = (*(*iter)->expression())->as<BinaryExpression>();
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400811 vectorize(b, iter, bin.fRight->fType, &bin.fLeft, outUpdated, outNeedsRescan);
812}
813
814/**
815 * Given a binary expression of the form vec<n>(x) <op> y, deletes the left side and vectorizes the
816 * right to yield vec<n>(y).
817 */
818static void vectorize_right(BasicBlock* b,
819 std::vector<BasicBlock::Node>::iterator* iter,
820 bool* outUpdated,
821 bool* outNeedsRescan) {
John Stilesa5a97b42020-08-18 11:19:07 -0400822 BinaryExpression& bin = (*(*iter)->expression())->as<BinaryExpression>();
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400823 vectorize(b, iter, bin.fLeft->fType, &bin.fRight, outUpdated, outNeedsRescan);
824}
825
826// Mark that an expression which we were writing to is no longer being written to
John Stilesa5a97b42020-08-18 11:19:07 -0400827static void clear_write(Expression& expr) {
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400828 switch (expr.fKind) {
829 case Expression::kVariableReference_Kind: {
John Stilesa5a97b42020-08-18 11:19:07 -0400830 expr.as<VariableReference>().setRefKind(VariableReference::kRead_RefKind);
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400831 break;
832 }
833 case Expression::kFieldAccess_Kind:
John Stilesa5a97b42020-08-18 11:19:07 -0400834 clear_write(*expr.as<FieldAccess>().fBase);
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400835 break;
836 case Expression::kSwizzle_Kind:
John Stilesa5a97b42020-08-18 11:19:07 -0400837 clear_write(*expr.as<Swizzle>().fBase);
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400838 break;
839 case Expression::kIndex_Kind:
John Stilesa5a97b42020-08-18 11:19:07 -0400840 clear_write(*expr.as<IndexExpression>().fBase);
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400841 break;
842 default:
843 ABORT("shouldn't be writing to this kind of expression\n");
844 break;
845 }
846}
847
Ethan Nicholascb670962017-04-20 19:31:52 -0400848void Compiler::simplifyExpression(DefinitionMap& definitions,
849 BasicBlock& b,
850 std::vector<BasicBlock::Node>::iterator* iter,
851 std::unordered_set<const Variable*>* undefinedVariables,
852 bool* outUpdated,
853 bool* outNeedsRescan) {
854 Expression* expr = (*iter)->expression()->get();
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400855 SkASSERT(expr);
Ethan Nicholascb670962017-04-20 19:31:52 -0400856 if ((*iter)->fConstantPropagation) {
857 std::unique_ptr<Expression> optimized = expr->constantPropagate(*fIRGenerator, definitions);
858 if (optimized) {
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400859 *outUpdated = true;
Ethan Nicholascb670962017-04-20 19:31:52 -0400860 if (!try_replace_expression(&b, iter, &optimized)) {
861 *outNeedsRescan = true;
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400862 return;
Ethan Nicholascb670962017-04-20 19:31:52 -0400863 }
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400864 SkASSERT((*iter)->fKind == BasicBlock::Node::kExpression_Kind);
Ethan Nicholascb670962017-04-20 19:31:52 -0400865 expr = (*iter)->expression()->get();
Ethan Nicholascb670962017-04-20 19:31:52 -0400866 }
867 }
868 switch (expr->fKind) {
869 case Expression::kVariableReference_Kind: {
John Stilesa5a97b42020-08-18 11:19:07 -0400870 const VariableReference& ref = expr->as<VariableReference>();
Ethan Nicholas8f7e28f2018-03-26 14:24:27 -0400871 const Variable& var = ref.fVariable;
872 if (ref.refKind() != VariableReference::kWrite_RefKind &&
873 ref.refKind() != VariableReference::kPointer_RefKind &&
874 var.fStorage == Variable::kLocal_Storage && !definitions[&var] &&
Ethan Nicholascb670962017-04-20 19:31:52 -0400875 (*undefinedVariables).find(&var) == (*undefinedVariables).end()) {
876 (*undefinedVariables).insert(&var);
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000877 this->error(expr->fOffset,
878 "'" + var.fName + "' has not been assigned");
Ethan Nicholascb670962017-04-20 19:31:52 -0400879 }
880 break;
881 }
882 case Expression::kTernary_Kind: {
John Stiles403a3632020-08-20 12:11:48 -0400883 TernaryExpression* t = &expr->as<TernaryExpression>();
Ethan Nicholascb670962017-04-20 19:31:52 -0400884 if (t->fTest->fKind == Expression::kBoolLiteral_Kind) {
885 // ternary has a constant test, replace it with either the true or
886 // false branch
John Stiles403a3632020-08-20 12:11:48 -0400887 if (t->fTest->as<BoolLiteral>().fValue) {
Ethan Nicholascb670962017-04-20 19:31:52 -0400888 (*iter)->setExpression(std::move(t->fIfTrue));
889 } else {
890 (*iter)->setExpression(std::move(t->fIfFalse));
891 }
892 *outUpdated = true;
893 *outNeedsRescan = true;
894 }
895 break;
896 }
897 case Expression::kBinary_Kind: {
John Stiles403a3632020-08-20 12:11:48 -0400898 BinaryExpression* bin = &expr->as<BinaryExpression>();
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400899 if (dead_assignment(*bin)) {
900 delete_left(&b, iter, outUpdated, outNeedsRescan);
901 break;
902 }
903 // collapse useless expressions like x * 1 or x + 0
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400904 if (((bin->fLeft->fType.kind() != Type::kScalar_Kind) &&
905 (bin->fLeft->fType.kind() != Type::kVector_Kind)) ||
906 ((bin->fRight->fType.kind() != Type::kScalar_Kind) &&
907 (bin->fRight->fType.kind() != Type::kVector_Kind))) {
908 break;
909 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400910 switch (bin->fOperator) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400911 case Token::Kind::TK_STAR:
Ethan Nicholascb670962017-04-20 19:31:52 -0400912 if (is_constant(*bin->fLeft, 1)) {
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400913 if (bin->fLeft->fType.kind() == Type::kVector_Kind &&
914 bin->fRight->fType.kind() == Type::kScalar_Kind) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400915 // float4(1) * x -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400916 vectorize_right(&b, iter, outUpdated, outNeedsRescan);
917 } else {
918 // 1 * x -> x
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400919 // 1 * float4(x) -> float4(x)
920 // float4(1) * float4(x) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400921 delete_left(&b, iter, outUpdated, outNeedsRescan);
922 }
923 }
924 else if (is_constant(*bin->fLeft, 0)) {
925 if (bin->fLeft->fType.kind() == Type::kScalar_Kind &&
Ethan Nicholas08dae922018-01-23 10:31:56 -0500926 bin->fRight->fType.kind() == Type::kVector_Kind &&
927 !bin->fRight->hasSideEffects()) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400928 // 0 * float4(x) -> float4(0)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400929 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
930 } else {
931 // 0 * x -> 0
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400932 // float4(0) * x -> float4(0)
933 // float4(0) * float4(x) -> float4(0)
Ethan Nicholas51493ee2017-12-11 12:34:33 -0500934 if (!bin->fRight->hasSideEffects()) {
935 delete_right(&b, iter, outUpdated, outNeedsRescan);
936 }
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400937 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400938 }
939 else if (is_constant(*bin->fRight, 1)) {
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400940 if (bin->fLeft->fType.kind() == Type::kScalar_Kind &&
941 bin->fRight->fType.kind() == Type::kVector_Kind) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400942 // x * float4(1) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400943 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
944 } else {
945 // x * 1 -> x
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400946 // float4(x) * 1 -> float4(x)
947 // float4(x) * float4(1) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400948 delete_right(&b, iter, outUpdated, outNeedsRescan);
949 }
950 }
951 else if (is_constant(*bin->fRight, 0)) {
952 if (bin->fLeft->fType.kind() == Type::kVector_Kind &&
Ethan Nicholas08dae922018-01-23 10:31:56 -0500953 bin->fRight->fType.kind() == Type::kScalar_Kind &&
954 !bin->fLeft->hasSideEffects()) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400955 // float4(x) * 0 -> float4(0)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400956 vectorize_right(&b, iter, outUpdated, outNeedsRescan);
957 } else {
958 // x * 0 -> 0
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400959 // x * float4(0) -> float4(0)
960 // float4(x) * float4(0) -> float4(0)
Ethan Nicholas51493ee2017-12-11 12:34:33 -0500961 if (!bin->fLeft->hasSideEffects()) {
962 delete_left(&b, iter, outUpdated, outNeedsRescan);
963 }
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400964 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400965 }
966 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400967 case Token::Kind::TK_PLUS:
Ethan Nicholascb670962017-04-20 19:31:52 -0400968 if (is_constant(*bin->fLeft, 0)) {
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400969 if (bin->fLeft->fType.kind() == Type::kVector_Kind &&
970 bin->fRight->fType.kind() == Type::kScalar_Kind) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400971 // float4(0) + x -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400972 vectorize_right(&b, iter, outUpdated, outNeedsRescan);
973 } else {
974 // 0 + x -> x
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400975 // 0 + float4(x) -> float4(x)
976 // float4(0) + float4(x) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400977 delete_left(&b, iter, outUpdated, outNeedsRescan);
978 }
979 } else if (is_constant(*bin->fRight, 0)) {
980 if (bin->fLeft->fType.kind() == Type::kScalar_Kind &&
981 bin->fRight->fType.kind() == Type::kVector_Kind) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400982 // x + float4(0) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400983 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
984 } else {
985 // x + 0 -> x
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400986 // float4(x) + 0 -> float4(x)
987 // float4(x) + float4(0) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400988 delete_right(&b, iter, outUpdated, outNeedsRescan);
989 }
Ethan Nicholas56e42712017-04-21 10:23:37 -0400990 }
991 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400992 case Token::Kind::TK_MINUS:
Ethan Nicholas56e42712017-04-21 10:23:37 -0400993 if (is_constant(*bin->fRight, 0)) {
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400994 if (bin->fLeft->fType.kind() == Type::kScalar_Kind &&
995 bin->fRight->fType.kind() == Type::kVector_Kind) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400996 // x - float4(0) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400997 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
998 } else {
999 // x - 0 -> x
Ethan Nicholas5af9ea32017-07-28 15:19:46 -04001000 // float4(x) - 0 -> float4(x)
1001 // float4(x) - float4(0) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -04001002 delete_right(&b, iter, outUpdated, outNeedsRescan);
1003 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001004 }
1005 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001006 case Token::Kind::TK_SLASH:
Ethan Nicholascb670962017-04-20 19:31:52 -04001007 if (is_constant(*bin->fRight, 1)) {
Ethan Nicholasfe53e582017-04-27 16:24:51 -04001008 if (bin->fLeft->fType.kind() == Type::kScalar_Kind &&
1009 bin->fRight->fType.kind() == Type::kVector_Kind) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -04001010 // x / float4(1) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -04001011 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
1012 } else {
1013 // x / 1 -> x
Ethan Nicholas5af9ea32017-07-28 15:19:46 -04001014 // float4(x) / 1 -> float4(x)
1015 // float4(x) / float4(1) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -04001016 delete_right(&b, iter, outUpdated, outNeedsRescan);
1017 }
1018 } else if (is_constant(*bin->fLeft, 0)) {
1019 if (bin->fLeft->fType.kind() == Type::kScalar_Kind &&
Ethan Nicholas08dae922018-01-23 10:31:56 -05001020 bin->fRight->fType.kind() == Type::kVector_Kind &&
1021 !bin->fRight->hasSideEffects()) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -04001022 // 0 / float4(x) -> float4(0)
Ethan Nicholasfe53e582017-04-27 16:24:51 -04001023 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
1024 } else {
1025 // 0 / x -> 0
Ethan Nicholas5af9ea32017-07-28 15:19:46 -04001026 // float4(0) / x -> float4(0)
1027 // float4(0) / float4(x) -> float4(0)
Ethan Nicholas51493ee2017-12-11 12:34:33 -05001028 if (!bin->fRight->hasSideEffects()) {
1029 delete_right(&b, iter, outUpdated, outNeedsRescan);
1030 }
Ethan Nicholasfe53e582017-04-27 16:24:51 -04001031 }
1032 }
1033 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001034 case Token::Kind::TK_PLUSEQ:
Ethan Nicholasfe53e582017-04-27 16:24:51 -04001035 if (is_constant(*bin->fRight, 0)) {
1036 clear_write(*bin->fLeft);
1037 delete_right(&b, iter, outUpdated, outNeedsRescan);
1038 }
1039 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001040 case Token::Kind::TK_MINUSEQ:
Ethan Nicholasfe53e582017-04-27 16:24:51 -04001041 if (is_constant(*bin->fRight, 0)) {
1042 clear_write(*bin->fLeft);
1043 delete_right(&b, iter, outUpdated, outNeedsRescan);
1044 }
1045 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001046 case Token::Kind::TK_STAREQ:
Ethan Nicholasfe53e582017-04-27 16:24:51 -04001047 if (is_constant(*bin->fRight, 1)) {
1048 clear_write(*bin->fLeft);
1049 delete_right(&b, iter, outUpdated, outNeedsRescan);
1050 }
1051 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001052 case Token::Kind::TK_SLASHEQ:
Ethan Nicholasfe53e582017-04-27 16:24:51 -04001053 if (is_constant(*bin->fRight, 1)) {
1054 clear_write(*bin->fLeft);
Ethan Nicholascb670962017-04-20 19:31:52 -04001055 delete_right(&b, iter, outUpdated, outNeedsRescan);
1056 }
1057 break;
1058 default:
1059 break;
1060 }
Ethan Nicholas409f6f02019-09-17 12:34:39 -04001061 break;
1062 }
1063 case Expression::kSwizzle_Kind: {
John Stiles403a3632020-08-20 12:11:48 -04001064 Swizzle& s = expr->as<Swizzle>();
Ethan Nicholas409f6f02019-09-17 12:34:39 -04001065 // detect identity swizzles like foo.rgba
1066 if ((int) s.fComponents.size() == s.fBase->fType.columns()) {
1067 bool identity = true;
1068 for (int i = 0; i < (int) s.fComponents.size(); ++i) {
1069 if (s.fComponents[i] != i) {
1070 identity = false;
1071 break;
1072 }
1073 }
1074 if (identity) {
1075 *outUpdated = true;
1076 if (!try_replace_expression(&b, iter, &s.fBase)) {
1077 *outNeedsRescan = true;
1078 return;
1079 }
1080 SkASSERT((*iter)->fKind == BasicBlock::Node::kExpression_Kind);
1081 break;
1082 }
1083 }
1084 // detect swizzles of swizzles, e.g. replace foo.argb.r000 with foo.a000
1085 if (s.fBase->fKind == Expression::kSwizzle_Kind) {
John Stilesa5a97b42020-08-18 11:19:07 -04001086 Swizzle& base = s.fBase->as<Swizzle>();
Ethan Nicholas409f6f02019-09-17 12:34:39 -04001087 std::vector<int> final;
1088 for (int c : s.fComponents) {
1089 if (c == SKSL_SWIZZLE_0 || c == SKSL_SWIZZLE_1) {
1090 final.push_back(c);
1091 } else {
1092 final.push_back(base.fComponents[c]);
1093 }
1094 }
1095 *outUpdated = true;
1096 std::unique_ptr<Expression> replacement(new Swizzle(*fContext, base.fBase->clone(),
1097 std::move(final)));
1098 if (!try_replace_expression(&b, iter, &replacement)) {
1099 *outNeedsRescan = true;
1100 return;
1101 }
1102 SkASSERT((*iter)->fKind == BasicBlock::Node::kExpression_Kind);
Ethan Nicholas409f6f02019-09-17 12:34:39 -04001103 }
John Stiles30212b72020-06-11 17:55:07 -04001104 break;
Ethan Nicholascb670962017-04-20 19:31:52 -04001105 }
1106 default:
1107 break;
1108 }
1109}
1110
John Stiles92219b42020-06-15 12:32:24 -04001111// Implementation-detail recursive helper function for `contains_conditional_break`.
1112static bool contains_conditional_break_impl(Statement& s, bool inConditional) {
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001113 switch (s.fKind) {
1114 case Statement::kBlock_Kind:
John Stilesa5a97b42020-08-18 11:19:07 -04001115 for (const std::unique_ptr<Statement>& sub : s.as<Block>().fStatements) {
John Stiles92219b42020-06-15 12:32:24 -04001116 if (contains_conditional_break_impl(*sub, inConditional)) {
Ethan Nicholas5005a222018-08-24 13:06:27 -04001117 return true;
1118 }
1119 }
1120 return false;
John Stiles92219b42020-06-15 12:32:24 -04001121
Ethan Nicholas5005a222018-08-24 13:06:27 -04001122 case Statement::kBreak_Kind:
1123 return inConditional;
John Stiles92219b42020-06-15 12:32:24 -04001124
Ethan Nicholas5005a222018-08-24 13:06:27 -04001125 case Statement::kIf_Kind: {
John Stilesa5a97b42020-08-18 11:19:07 -04001126 const IfStatement& i = s.as<IfStatement>();
John Stiles92219b42020-06-15 12:32:24 -04001127 return contains_conditional_break_impl(*i.fIfTrue, /*inConditional=*/true) ||
1128 (i.fIfFalse &&
1129 contains_conditional_break_impl(*i.fIfFalse, /*inConditional=*/true));
Ethan Nicholas5005a222018-08-24 13:06:27 -04001130 }
John Stiles92219b42020-06-15 12:32:24 -04001131
Ethan Nicholas5005a222018-08-24 13:06:27 -04001132 default:
1133 return false;
1134 }
1135}
1136
John Stiles92219b42020-06-15 12:32:24 -04001137// Returns true if this statement could potentially execute a break at the current level. We ignore
1138// nested loops and switches, since any breaks inside of them will merely break the loop / switch.
1139static bool contains_conditional_break(Statement& s) {
1140 return contains_conditional_break_impl(s, /*inConditional=*/false);
1141}
1142
Ethan Nicholas5005a222018-08-24 13:06:27 -04001143// returns true if this statement definitely executes a break at the current level (we ignore
1144// nested loops and switches, since any breaks inside of them will merely break the loop / switch)
1145static bool contains_unconditional_break(Statement& s) {
1146 switch (s.fKind) {
1147 case Statement::kBlock_Kind:
John Stiles92219b42020-06-15 12:32:24 -04001148 for (const std::unique_ptr<Statement>& sub : static_cast<Block&>(s).fStatements) {
Ethan Nicholas5005a222018-08-24 13:06:27 -04001149 if (contains_unconditional_break(*sub)) {
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001150 return true;
1151 }
1152 }
1153 return false;
John Stiles92219b42020-06-15 12:32:24 -04001154
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001155 case Statement::kBreak_Kind:
1156 return true;
John Stiles92219b42020-06-15 12:32:24 -04001157
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001158 default:
1159 return false;
1160 }
1161}
1162
John Stiles92219b42020-06-15 12:32:24 -04001163static void move_all_but_break(std::unique_ptr<Statement>& stmt,
1164 std::vector<std::unique_ptr<Statement>>* target) {
Ethan Nicholas739e1ca2020-06-11 12:16:14 -04001165 switch (stmt->fKind) {
John Stiles92219b42020-06-15 12:32:24 -04001166 case Statement::kBlock_Kind: {
1167 // Recurse into the block.
1168 Block& block = static_cast<Block&>(*stmt);
1169
1170 std::vector<std::unique_ptr<Statement>> blockStmts;
1171 blockStmts.reserve(block.fStatements.size());
1172 for (std::unique_ptr<Statement>& statementInBlock : block.fStatements) {
1173 move_all_but_break(statementInBlock, &blockStmts);
Ethan Nicholas739e1ca2020-06-11 12:16:14 -04001174 }
John Stiles92219b42020-06-15 12:32:24 -04001175
1176 target->push_back(std::make_unique<Block>(block.fOffset, std::move(blockStmts),
1177 block.fSymbols, block.fIsScope));
Ethan Nicholas739e1ca2020-06-11 12:16:14 -04001178 break;
John Stiles92219b42020-06-15 12:32:24 -04001179 }
1180
Ethan Nicholas739e1ca2020-06-11 12:16:14 -04001181 case Statement::kBreak_Kind:
John Stiles92219b42020-06-15 12:32:24 -04001182 // Do not append a break to the target.
1183 break;
1184
Ethan Nicholas739e1ca2020-06-11 12:16:14 -04001185 default:
John Stiles92219b42020-06-15 12:32:24 -04001186 // Append normal statements to the target.
1187 target->push_back(std::move(stmt));
1188 break;
Ethan Nicholas739e1ca2020-06-11 12:16:14 -04001189 }
1190}
1191
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001192// Returns a block containing all of the statements that will be run if the given case matches
1193// (which, owing to the statements being owned by unique_ptrs, means the switch itself will be
1194// broken by this call and must then be discarded).
1195// Returns null (and leaves the switch unmodified) if no such simple reduction is possible, such as
1196// when break statements appear inside conditionals.
John Stiles92219b42020-06-15 12:32:24 -04001197static std::unique_ptr<Statement> block_for_case(SwitchStatement* switchStatement,
1198 SwitchCase* caseToCapture) {
1199 // We have to be careful to not move any of the pointers until after we're sure we're going to
1200 // succeed, so before we make any changes at all, we check the switch-cases to decide on a plan
1201 // of action. First, find the switch-case we are interested in.
1202 auto iter = switchStatement->fCases.begin();
1203 for (; iter != switchStatement->fCases.end(); ++iter) {
1204 if (iter->get() == caseToCapture) {
1205 break;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001206 }
John Stiles92219b42020-06-15 12:32:24 -04001207 }
1208
1209 // Next, walk forward through the rest of the switch. If we find a conditional break, we're
1210 // stuck and can't simplify at all. If we find an unconditional break, we have a range of
1211 // statements that we can use for simplification.
1212 auto startIter = iter;
1213 Statement* unconditionalBreakStmt = nullptr;
1214 for (; iter != switchStatement->fCases.end(); ++iter) {
1215 for (std::unique_ptr<Statement>& stmt : (*iter)->fStatements) {
1216 if (contains_conditional_break(*stmt)) {
1217 // We can't reduce switch-cases to a block when they have conditional breaks.
1218 return nullptr;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001219 }
John Stiles92219b42020-06-15 12:32:24 -04001220
1221 if (contains_unconditional_break(*stmt)) {
1222 // We found an unconditional break. We can use this block, but we need to strip
1223 // out the break statement.
1224 unconditionalBreakStmt = stmt.get();
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001225 break;
1226 }
1227 }
John Stiles92219b42020-06-15 12:32:24 -04001228
1229 if (unconditionalBreakStmt != nullptr) {
1230 break;
1231 }
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001232 }
John Stiles92219b42020-06-15 12:32:24 -04001233
1234 // We fell off the bottom of the switch or encountered a break. We know the range of statements
1235 // that we need to move over, and we know it's safe to do so.
1236 std::vector<std::unique_ptr<Statement>> caseStmts;
1237
1238 // We can move over most of the statements as-is.
1239 while (startIter != iter) {
1240 for (std::unique_ptr<Statement>& stmt : (*startIter)->fStatements) {
1241 caseStmts.push_back(std::move(stmt));
1242 }
1243 ++startIter;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001244 }
John Stiles92219b42020-06-15 12:32:24 -04001245
1246 // If we found an unconditional break at the end, we need to move what we can while avoiding
1247 // that break.
1248 if (unconditionalBreakStmt != nullptr) {
1249 for (std::unique_ptr<Statement>& stmt : (*startIter)->fStatements) {
1250 if (stmt.get() == unconditionalBreakStmt) {
1251 move_all_but_break(stmt, &caseStmts);
1252 unconditionalBreakStmt = nullptr;
1253 break;
1254 }
1255
1256 caseStmts.push_back(std::move(stmt));
1257 }
1258 }
1259
1260 SkASSERT(unconditionalBreakStmt == nullptr); // Verify that we fixed the unconditional break.
1261
1262 // Return our newly-synthesized block.
1263 return std::make_unique<Block>(/*offset=*/-1, std::move(caseStmts), switchStatement->fSymbols);
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001264}
1265
Ethan Nicholascb670962017-04-20 19:31:52 -04001266void Compiler::simplifyStatement(DefinitionMap& definitions,
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001267 BasicBlock& b,
1268 std::vector<BasicBlock::Node>::iterator* iter,
1269 std::unordered_set<const Variable*>* undefinedVariables,
1270 bool* outUpdated,
1271 bool* outNeedsRescan) {
Ethan Nicholascb670962017-04-20 19:31:52 -04001272 Statement* stmt = (*iter)->statement()->get();
1273 switch (stmt->fKind) {
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001274 case Statement::kVarDeclaration_Kind: {
John Stilesa5a97b42020-08-18 11:19:07 -04001275 const auto& varDecl = stmt->as<VarDeclaration>();
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001276 if (varDecl.fVar->dead() &&
1277 (!varDecl.fValue ||
1278 !varDecl.fValue->hasSideEffects())) {
1279 if (varDecl.fValue) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001280 SkASSERT((*iter)->statement()->get() == stmt);
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001281 if (!b.tryRemoveExpressionBefore(iter, varDecl.fValue.get())) {
1282 *outNeedsRescan = true;
Ethan Nicholascb670962017-04-20 19:31:52 -04001283 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001284 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001285 (*iter)->setStatement(std::unique_ptr<Statement>(new Nop()));
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001286 *outUpdated = true;
Ethan Nicholascb670962017-04-20 19:31:52 -04001287 }
1288 break;
1289 }
1290 case Statement::kIf_Kind: {
John Stilesa5a97b42020-08-18 11:19:07 -04001291 IfStatement& i = stmt->as<IfStatement>();
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001292 if (i.fTest->fKind == Expression::kBoolLiteral_Kind) {
1293 // constant if, collapse down to a single branch
John Stilesa5a97b42020-08-18 11:19:07 -04001294 if (i.fTest->as<BoolLiteral>().fValue) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001295 SkASSERT(i.fIfTrue);
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001296 (*iter)->setStatement(std::move(i.fIfTrue));
1297 } else {
1298 if (i.fIfFalse) {
1299 (*iter)->setStatement(std::move(i.fIfFalse));
1300 } else {
1301 (*iter)->setStatement(std::unique_ptr<Statement>(new Nop()));
1302 }
1303 }
1304 *outUpdated = true;
1305 *outNeedsRescan = true;
1306 break;
1307 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001308 if (i.fIfFalse && i.fIfFalse->isEmpty()) {
1309 // else block doesn't do anything, remove it
1310 i.fIfFalse.reset();
1311 *outUpdated = true;
1312 *outNeedsRescan = true;
1313 }
1314 if (!i.fIfFalse && i.fIfTrue->isEmpty()) {
1315 // if block doesn't do anything, no else block
1316 if (i.fTest->hasSideEffects()) {
1317 // test has side effects, keep it
1318 (*iter)->setStatement(std::unique_ptr<Statement>(
1319 new ExpressionStatement(std::move(i.fTest))));
1320 } else {
1321 // no if, no else, no test side effects, kill the whole if
1322 // statement
1323 (*iter)->setStatement(std::unique_ptr<Statement>(new Nop()));
1324 }
1325 *outUpdated = true;
1326 *outNeedsRescan = true;
1327 }
1328 break;
1329 }
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001330 case Statement::kSwitch_Kind: {
John Stilesa5a97b42020-08-18 11:19:07 -04001331 SwitchStatement& s = stmt->as<SwitchStatement>();
Brian Osmanb6b95732020-06-30 11:44:27 -04001332 if (s.fValue->isCompileTimeConstant()) {
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001333 // switch is constant, replace it with the case that matches
1334 bool found = false;
1335 SwitchCase* defaultCase = nullptr;
John Stiles9d944232020-08-19 09:56:49 -04001336 for (const std::unique_ptr<SwitchCase>& c : s.fCases) {
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001337 if (!c->fValue) {
1338 defaultCase = c.get();
1339 continue;
1340 }
John Stiles9d944232020-08-19 09:56:49 -04001341 if (is_constant<int64_t>(*s.fValue, c->fValue->getConstantInt())) {
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001342 std::unique_ptr<Statement> newBlock = block_for_case(&s, c.get());
1343 if (newBlock) {
1344 (*iter)->setStatement(std::move(newBlock));
John Stiles9d944232020-08-19 09:56:49 -04001345 found = true;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001346 break;
1347 } else {
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -04001348 if (s.fIsStatic && !(fFlags & kPermitInvalidStaticTests_Flag)) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001349 this->error(s.fOffset,
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001350 "static switch contains non-static conditional break");
1351 s.fIsStatic = false;
1352 }
1353 return; // can't simplify
1354 }
1355 }
1356 }
1357 if (!found) {
1358 // no matching case. use default if it exists, or kill the whole thing
1359 if (defaultCase) {
1360 std::unique_ptr<Statement> newBlock = block_for_case(&s, defaultCase);
1361 if (newBlock) {
1362 (*iter)->setStatement(std::move(newBlock));
1363 } else {
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -04001364 if (s.fIsStatic && !(fFlags & kPermitInvalidStaticTests_Flag)) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001365 this->error(s.fOffset,
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001366 "static switch contains non-static conditional break");
1367 s.fIsStatic = false;
1368 }
1369 return; // can't simplify
1370 }
1371 } else {
1372 (*iter)->setStatement(std::unique_ptr<Statement>(new Nop()));
1373 }
1374 }
1375 *outUpdated = true;
1376 *outNeedsRescan = true;
1377 }
1378 break;
1379 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001380 case Statement::kExpression_Kind: {
John Stilesa5a97b42020-08-18 11:19:07 -04001381 ExpressionStatement& e = stmt->as<ExpressionStatement>();
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001382 SkASSERT((*iter)->statement()->get() == &e);
Ethan Nicholascb670962017-04-20 19:31:52 -04001383 if (!e.fExpression->hasSideEffects()) {
1384 // Expression statement with no side effects, kill it
1385 if (!b.tryRemoveExpressionBefore(iter, e.fExpression.get())) {
1386 *outNeedsRescan = true;
1387 }
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001388 SkASSERT((*iter)->statement()->get() == stmt);
Ethan Nicholascb670962017-04-20 19:31:52 -04001389 (*iter)->setStatement(std::unique_ptr<Statement>(new Nop()));
1390 *outUpdated = true;
1391 }
1392 break;
1393 }
1394 default:
1395 break;
1396 }
1397}
1398
1399void Compiler::scanCFG(FunctionDefinition& f) {
1400 CFG cfg = CFGGenerator().getCFG(f);
1401 this->computeDataFlow(&cfg);
ethannicholas22f939e2016-10-13 13:25:34 -07001402
1403 // check for unreachable code
1404 for (size_t i = 0; i < cfg.fBlocks.size(); i++) {
Mike Klein6ad99092016-10-26 10:35:22 -04001405 if (i != cfg.fStart && !cfg.fBlocks[i].fEntrances.size() &&
ethannicholas22f939e2016-10-13 13:25:34 -07001406 cfg.fBlocks[i].fNodes.size()) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001407 int offset;
Ethan Nicholas86a43402017-01-19 13:32:00 -05001408 switch (cfg.fBlocks[i].fNodes[0].fKind) {
1409 case BasicBlock::Node::kStatement_Kind:
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001410 offset = (*cfg.fBlocks[i].fNodes[0].statement())->fOffset;
Ethan Nicholas86a43402017-01-19 13:32:00 -05001411 break;
1412 case BasicBlock::Node::kExpression_Kind:
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001413 offset = (*cfg.fBlocks[i].fNodes[0].expression())->fOffset;
Ethan Nicholas70728ef2020-05-28 07:09:00 -04001414 if ((*cfg.fBlocks[i].fNodes[0].expression())->fKind ==
1415 Expression::kBoolLiteral_Kind) {
1416 // Function inlining can generate do { ... } while(false) loops which always
1417 // break, so the boolean condition is considered unreachable. Since not
1418 // being able to reach a literal is a non-issue in the first place, we
1419 // don't report an error in this case.
1420 continue;
1421 }
Ethan Nicholas86a43402017-01-19 13:32:00 -05001422 break;
1423 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001424 this->error(offset, String("unreachable"));
ethannicholas22f939e2016-10-13 13:25:34 -07001425 }
1426 }
1427 if (fErrorCount) {
1428 return;
1429 }
1430
Ethan Nicholascb670962017-04-20 19:31:52 -04001431 // check for dead code & undefined variables, perform constant propagation
1432 std::unordered_set<const Variable*> undefinedVariables;
1433 bool updated;
1434 bool needsRescan = false;
1435 do {
1436 if (needsRescan) {
1437 cfg = CFGGenerator().getCFG(f);
1438 this->computeDataFlow(&cfg);
1439 needsRescan = false;
Ethan Nicholas113628d2017-02-02 16:11:39 -05001440 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001441
1442 updated = false;
Ethan Nicholas1de14812020-06-19 15:32:49 -04001443 bool first = true;
Ethan Nicholascb670962017-04-20 19:31:52 -04001444 for (BasicBlock& b : cfg.fBlocks) {
Ethan Nicholas1de14812020-06-19 15:32:49 -04001445 if (!first && b.fEntrances.empty()) {
1446 // Block was reachable before optimization, but has since become unreachable. In
1447 // addition to being dead code, it's broken - since control flow can't reach it, no
1448 // prior variable definitions can reach it, and therefore variables might look to
1449 // have not been properly assigned. Kill it.
1450 for (BasicBlock::Node& node : b.fNodes) {
1451 if (node.fKind == BasicBlock::Node::kStatement_Kind &&
1452 (*node.statement())->fKind != Statement::kNop_Kind) {
1453 node.setStatement(std::unique_ptr<Statement>(new Nop()));
1454 }
1455 }
1456 continue;
1457 }
1458 first = false;
Ethan Nicholascb670962017-04-20 19:31:52 -04001459 DefinitionMap definitions = b.fBefore;
1460
1461 for (auto iter = b.fNodes.begin(); iter != b.fNodes.end() && !needsRescan; ++iter) {
1462 if (iter->fKind == BasicBlock::Node::kExpression_Kind) {
1463 this->simplifyExpression(definitions, b, &iter, &undefinedVariables, &updated,
1464 &needsRescan);
1465 } else {
1466 this->simplifyStatement(definitions, b, &iter, &undefinedVariables, &updated,
1467 &needsRescan);
1468 }
Ethan Nicholas4b330df2017-05-17 10:52:55 -04001469 if (needsRescan) {
1470 break;
1471 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001472 this->addDefinitions(*iter, &definitions);
1473 }
1474 }
1475 } while (updated);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001476 SkASSERT(!needsRescan);
ethannicholas22f939e2016-10-13 13:25:34 -07001477
Ethan Nicholas91a10532017-06-22 11:24:38 -04001478 // verify static ifs & switches, clean up dead variable decls
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001479 for (BasicBlock& b : cfg.fBlocks) {
1480 DefinitionMap definitions = b.fBefore;
1481
Ethan Nicholas91a10532017-06-22 11:24:38 -04001482 for (auto iter = b.fNodes.begin(); iter != b.fNodes.end() && !needsRescan;) {
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001483 if (iter->fKind == BasicBlock::Node::kStatement_Kind) {
1484 const Statement& s = **iter->statement();
1485 switch (s.fKind) {
1486 case Statement::kIf_Kind:
John Stilesa5a97b42020-08-18 11:19:07 -04001487 if (s.as<IfStatement>().fIsStatic &&
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -04001488 !(fFlags & kPermitInvalidStaticTests_Flag)) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001489 this->error(s.fOffset, "static if has non-static test");
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001490 }
Ethan Nicholas91a10532017-06-22 11:24:38 -04001491 ++iter;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001492 break;
1493 case Statement::kSwitch_Kind:
John Stilesa5a97b42020-08-18 11:19:07 -04001494 if (s.as<SwitchStatement>().fIsStatic &&
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -04001495 !(fFlags & kPermitInvalidStaticTests_Flag)) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001496 this->error(s.fOffset, "static switch has non-static test");
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001497 }
Ethan Nicholas91a10532017-06-22 11:24:38 -04001498 ++iter;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001499 break;
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001500 case Statement::kVarDeclarations_Kind: {
John Stilesa5a97b42020-08-18 11:19:07 -04001501 VarDeclarations& decls = *s.as<VarDeclarationsStatement>().fDeclaration;
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001502 for (auto varIter = decls.fVars.begin(); varIter != decls.fVars.end();) {
1503 if ((*varIter)->fKind == Statement::kNop_Kind) {
1504 varIter = decls.fVars.erase(varIter);
1505 } else {
1506 ++varIter;
1507 }
1508 }
1509 if (!decls.fVars.size()) {
1510 iter = b.fNodes.erase(iter);
1511 } else {
1512 ++iter;
1513 }
1514 break;
1515 }
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001516 default:
Ethan Nicholas91a10532017-06-22 11:24:38 -04001517 ++iter;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001518 break;
1519 }
Ethan Nicholas91a10532017-06-22 11:24:38 -04001520 } else {
1521 ++iter;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001522 }
1523 }
1524 }
1525
ethannicholas22f939e2016-10-13 13:25:34 -07001526 // check for missing return
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001527 if (f.fDeclaration.fReturnType != *fContext->fVoid_Type) {
ethannicholas22f939e2016-10-13 13:25:34 -07001528 if (cfg.fBlocks[cfg.fExit].fEntrances.size()) {
Ethan Nicholasdb80f692019-11-22 14:06:12 -05001529 this->error(f.fOffset, String("function '" + String(f.fDeclaration.fName) +
1530 "' can exit without returning a value"));
ethannicholas22f939e2016-10-13 13:25:34 -07001531 }
1532 }
1533}
1534
Ethan Nicholas91164d12019-05-15 15:29:54 -04001535void Compiler::registerExternalValue(ExternalValue* value) {
1536 fIRGenerator->fRootSymbolTable->addWithoutOwnership(value->fName, value);
1537}
1538
Ethan Nicholasc18bb512020-07-28 14:46:53 -04001539const Symbol* Compiler::takeOwnership(std::unique_ptr<const Symbol> symbol) {
John Stiles3ae071e2020-08-05 15:29:29 -04001540 return fIRGenerator->fRootSymbolTable->takeOwnershipOfSymbol(std::move(symbol));
Ethan Nicholas91164d12019-05-15 15:29:54 -04001541}
1542
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001543std::unique_ptr<Program> Compiler::convertProgram(Program::Kind kind, String text,
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001544 const Program::Settings& settings) {
ethannicholasb3058bd2016-07-01 08:22:01 -07001545 fErrorText = "";
1546 fErrorCount = 0;
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001547 std::vector<std::unique_ptr<ProgramElement>>* inherited;
ethannicholasd598f792016-07-25 10:08:54 -07001548 std::vector<std::unique_ptr<ProgramElement>> elements;
ethannicholasb3058bd2016-07-01 08:22:01 -07001549 switch (kind) {
1550 case Program::kVertex_Kind:
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001551 inherited = &fVertexInclude;
1552 fIRGenerator->fSymbolTable = fVertexSymbolTable;
John Stiles810c8cf2020-08-26 19:46:27 -04001553 fIRGenerator->fIntrinsics = fGPUIntrinsics.get();
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001554 fIRGenerator->start(&settings, inherited);
ethannicholasb3058bd2016-07-01 08:22:01 -07001555 break;
1556 case Program::kFragment_Kind:
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001557 inherited = &fFragmentInclude;
1558 fIRGenerator->fSymbolTable = fFragmentSymbolTable;
John Stiles810c8cf2020-08-26 19:46:27 -04001559 fIRGenerator->fIntrinsics = fGPUIntrinsics.get();
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001560 fIRGenerator->start(&settings, inherited);
ethannicholasb3058bd2016-07-01 08:22:01 -07001561 break;
Ethan Nicholas52cad152017-02-16 16:37:32 -05001562 case Program::kGeometry_Kind:
Ethan Nicholasc18bb512020-07-28 14:46:53 -04001563 this->loadGeometryIntrinsics();
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001564 inherited = &fGeometryInclude;
1565 fIRGenerator->fSymbolTable = fGeometrySymbolTable;
John Stiles810c8cf2020-08-26 19:46:27 -04001566 fIRGenerator->fIntrinsics = fGPUIntrinsics.get();
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001567 fIRGenerator->start(&settings, inherited);
Ethan Nicholas52cad152017-02-16 16:37:32 -05001568 break;
Ethan Nicholasb33fa3f2020-08-06 13:00:19 -04001569 case Program::kFragmentProcessor_Kind: {
Brian Osmandd496172020-08-08 08:17:18 -04001570#if !SKSL_STANDALONE
Ethan Nicholasc18bb512020-07-28 14:46:53 -04001571 {
1572 Rehydrator rehydrator(fContext.get(), fGpuSymbolTable, this,
1573 SKSL_INCLUDE_sksl_fp,
1574 SKSL_INCLUDE_sksl_fp_LENGTH);
1575 fFPSymbolTable = rehydrator.symbolTable();
1576 fFPInclude = rehydrator.elements();
1577 }
1578 inherited = &fFPInclude;
1579 fIRGenerator->fSymbolTable = fFPSymbolTable;
John Stiles810c8cf2020-08-26 19:46:27 -04001580 fIRGenerator->fIntrinsics = fGPUIntrinsics.get();
Ethan Nicholasc18bb512020-07-28 14:46:53 -04001581 fIRGenerator->start(&settings, inherited);
1582 break;
1583#else
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001584 inherited = nullptr;
Ethan Nicholas8da1e652019-05-24 11:01:59 -04001585 fIRGenerator->fSymbolTable = fGpuSymbolTable;
Ethan Nicholasb33fa3f2020-08-06 13:00:19 -04001586 fIRGenerator->start(&settings, /*inherited=*/nullptr, /*builtin=*/true);
John Stiles810c8cf2020-08-26 19:46:27 -04001587 fIRGenerator->fIntrinsics = fGPUIntrinsics.get();
Ethan Nicholasb33fa3f2020-08-06 13:00:19 -04001588 std::ifstream in(SKSL_FP_INCLUDE);
1589 std::string stdText{std::istreambuf_iterator<char>(in),
1590 std::istreambuf_iterator<char>()};
1591 if (in.rdstate()) {
1592 printf("error reading %s\n", SKSL_FP_INCLUDE);
1593 abort();
1594 }
1595 const String* source = fGpuSymbolTable->takeOwnershipOfString(
1596 std::make_unique<String>(stdText.c_str()));
1597 fIRGenerator->convertProgram(kind, source->c_str(), source->length(), &elements);
Ethan Nicholasc18bb512020-07-28 14:46:53 -04001598 fIRGenerator->fIsBuiltinCode = false;
Ethan Nicholas762466e2017-06-29 10:03:38 -04001599 break;
Ethan Nicholasc18bb512020-07-28 14:46:53 -04001600#endif
Ethan Nicholasb33fa3f2020-08-06 13:00:19 -04001601 }
Ethan Nicholas8da1e652019-05-24 11:01:59 -04001602 case Program::kPipelineStage_Kind:
Ethan Nicholasc18bb512020-07-28 14:46:53 -04001603 this->loadPipelineIntrinsics();
Ethan Nicholas8da1e652019-05-24 11:01:59 -04001604 inherited = &fPipelineInclude;
1605 fIRGenerator->fSymbolTable = fPipelineSymbolTable;
John Stiles810c8cf2020-08-26 19:46:27 -04001606 fIRGenerator->fIntrinsics = fGPUIntrinsics.get();
Ethan Nicholas8da1e652019-05-24 11:01:59 -04001607 fIRGenerator->start(&settings, inherited);
1608 break;
Ethan Nicholas746035a2019-04-23 13:31:09 -04001609 case Program::kGeneric_Kind:
Ethan Nicholasc18bb512020-07-28 14:46:53 -04001610 this->loadInterpreterIntrinsics();
Ethan Nicholas8da1e652019-05-24 11:01:59 -04001611 inherited = &fInterpreterInclude;
1612 fIRGenerator->fSymbolTable = fInterpreterSymbolTable;
John Stiles810c8cf2020-08-26 19:46:27 -04001613 fIRGenerator->fIntrinsics = fInterpreterIntrinsics.get();
Ethan Nicholas8da1e652019-05-24 11:01:59 -04001614 fIRGenerator->start(&settings, inherited);
Ethan Nicholas0d997662019-04-08 09:46:01 -04001615 break;
ethannicholasb3058bd2016-07-01 08:22:01 -07001616 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001617 std::unique_ptr<String> textPtr(new String(std::move(text)));
1618 fSource = textPtr.get();
Ethan Nicholasc18bb512020-07-28 14:46:53 -04001619 fIRGenerator->convertProgram(kind, textPtr->c_str(), textPtr->size(), &elements);
John Stilesfbd050b2020-08-03 13:21:46 -04001620 auto result = std::make_unique<Program>(kind,
1621 std::move(textPtr),
1622 settings,
1623 fContext,
1624 inherited,
1625 std::move(elements),
1626 fIRGenerator->fSymbolTable,
1627 fIRGenerator->fInputs);
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001628 if (fErrorCount) {
1629 return nullptr;
1630 }
1631 return result;
1632}
1633
Ethan Nicholas00543112018-07-31 09:44:36 -04001634bool Compiler::optimize(Program& program) {
1635 SkASSERT(!fErrorCount);
1636 if (!program.fIsOptimized) {
1637 program.fIsOptimized = true;
1638 fIRGenerator->fKind = program.fKind;
1639 fIRGenerator->fSettings = &program.fSettings;
1640 for (auto& element : program) {
1641 if (element.fKind == ProgramElement::kFunction_Kind) {
John Stiles3dc0da62020-08-19 17:48:31 -04001642 this->scanCFG(element.as<FunctionDefinition>());
Ethan Nicholas00543112018-07-31 09:44:36 -04001643 }
1644 }
Ethan Nicholase8ad02c2020-06-03 16:58:20 -04001645 // we wait until after analysis to remove dead functions so that we still report errors
1646 // even in unused code
1647 if (program.fSettings.fRemoveDeadFunctions) {
1648 for (auto iter = program.fElements.begin(); iter != program.fElements.end(); ) {
1649 if ((*iter)->fKind == ProgramElement::kFunction_Kind) {
John Stiles3dc0da62020-08-19 17:48:31 -04001650 const FunctionDefinition& f = (*iter)->as<FunctionDefinition>();
Ethan Nicholase8ad02c2020-06-03 16:58:20 -04001651 if (!f.fDeclaration.fCallCount && f.fDeclaration.fName != "main") {
1652 iter = program.fElements.erase(iter);
1653 continue;
1654 }
1655 }
1656 ++iter;
1657 }
1658 }
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001659 if (program.fKind != Program::kFragmentProcessor_Kind) {
1660 for (auto iter = program.fElements.begin(); iter != program.fElements.end();) {
1661 if ((*iter)->fKind == ProgramElement::kVar_Kind) {
John Stiles3dc0da62020-08-19 17:48:31 -04001662 VarDeclarations& vars = (*iter)->as<VarDeclarations>();
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001663 for (auto varIter = vars.fVars.begin(); varIter != vars.fVars.end();) {
John Stiles403a3632020-08-20 12:11:48 -04001664 const Variable& var = *(*varIter)->as<VarDeclaration>().fVar;
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001665 if (var.dead()) {
1666 varIter = vars.fVars.erase(varIter);
1667 } else {
1668 ++varIter;
1669 }
1670 }
1671 if (vars.fVars.size() == 0) {
1672 iter = program.fElements.erase(iter);
1673 continue;
1674 }
1675 }
1676 ++iter;
1677 }
1678 }
Ethan Nicholas00543112018-07-31 09:44:36 -04001679 }
1680 return fErrorCount == 0;
1681}
1682
Brian Osmanfb32ddf2019-06-18 10:14:20 -04001683#if defined(SKSL_STANDALONE) || SK_SUPPORT_GPU
1684
Ethan Nicholas00543112018-07-31 09:44:36 -04001685bool Compiler::toSPIRV(Program& program, OutputStream& out) {
1686 if (!this->optimize(program)) {
1687 return false;
1688 }
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001689#ifdef SK_ENABLE_SPIRV_VALIDATION
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001690 StringStream buffer;
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001691 fSource = program.fSource.get();
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001692 SPIRVCodeGenerator cg(fContext.get(), &program, this, &buffer);
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001693 bool result = cg.generateCode();
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001694 fSource = nullptr;
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001695 if (result) {
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001696 spvtools::SpirvTools tools(SPV_ENV_VULKAN_1_0);
Ethan Nicholas762466e2017-06-29 10:03:38 -04001697 const String& data = buffer.str();
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001698 SkASSERT(0 == data.size() % 4);
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001699 auto dumpmsg = [](spv_message_level_t, const char*, const spv_position_t&, const char* m) {
1700 SkDebugf("SPIR-V validation error: %s\n", m);
1701 };
1702 tools.SetMessageConsumer(dumpmsg);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001703 // Verify that the SPIR-V we produced is valid. If this SkASSERT fails, check the logs prior
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001704 // to the failure to see the validation errors.
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001705 SkAssertResult(tools.Validate((const uint32_t*) data.c_str(), data.size() / 4));
Ethan Nicholas762466e2017-06-29 10:03:38 -04001706 out.write(data.c_str(), data.size());
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001707 }
1708#else
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001709 fSource = program.fSource.get();
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001710 SPIRVCodeGenerator cg(fContext.get(), &program, this, &out);
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001711 bool result = cg.generateCode();
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001712 fSource = nullptr;
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001713#endif
Ethan Nicholasce33f102016-12-09 17:22:59 -05001714 return result;
1715}
1716
Ethan Nicholas00543112018-07-31 09:44:36 -04001717bool Compiler::toSPIRV(Program& program, String* out) {
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001718 StringStream buffer;
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001719 bool result = this->toSPIRV(program, buffer);
1720 if (result) {
Ethan Nicholas762466e2017-06-29 10:03:38 -04001721 *out = buffer.str();
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001722 }
1723 return result;
1724}
1725
Ethan Nicholas00543112018-07-31 09:44:36 -04001726bool Compiler::toGLSL(Program& program, OutputStream& out) {
1727 if (!this->optimize(program)) {
1728 return false;
1729 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001730 fSource = program.fSource.get();
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001731 GLSLCodeGenerator cg(fContext.get(), &program, this, &out);
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001732 bool result = cg.generateCode();
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001733 fSource = nullptr;
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001734 return result;
1735}
1736
Ethan Nicholas00543112018-07-31 09:44:36 -04001737bool Compiler::toGLSL(Program& program, String* out) {
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001738 StringStream buffer;
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001739 bool result = this->toGLSL(program, buffer);
1740 if (result) {
Ethan Nicholas762466e2017-06-29 10:03:38 -04001741 *out = buffer.str();
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001742 }
1743 return result;
1744}
1745
Brian Osmanc0243912020-02-19 15:35:26 -05001746bool Compiler::toHLSL(Program& program, String* out) {
1747 String spirv;
1748 if (!this->toSPIRV(program, &spirv)) {
1749 return false;
1750 }
1751
1752 return SPIRVtoHLSL(spirv, out);
1753}
1754
Ethan Nicholas00543112018-07-31 09:44:36 -04001755bool Compiler::toMetal(Program& program, OutputStream& out) {
1756 if (!this->optimize(program)) {
1757 return false;
1758 }
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001759 MetalCodeGenerator cg(fContext.get(), &program, this, &out);
Ethan Nicholascc305772017-10-13 16:17:45 -04001760 bool result = cg.generateCode();
Ethan Nicholascc305772017-10-13 16:17:45 -04001761 return result;
1762}
1763
Ethan Nicholas00543112018-07-31 09:44:36 -04001764bool Compiler::toMetal(Program& program, String* out) {
1765 if (!this->optimize(program)) {
1766 return false;
1767 }
Timothy Liangb8eeb802018-07-23 16:46:16 -04001768 StringStream buffer;
1769 bool result = this->toMetal(program, buffer);
1770 if (result) {
1771 *out = buffer.str();
1772 }
1773 return result;
1774}
1775
Ethan Nicholas2a479a52020-08-18 16:29:45 -04001776#if defined(SKSL_STANDALONE) || defined(GR_TEST_UTILS)
Ethan Nicholas00543112018-07-31 09:44:36 -04001777bool Compiler::toCPP(Program& program, String name, OutputStream& out) {
1778 if (!this->optimize(program)) {
1779 return false;
1780 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001781 fSource = program.fSource.get();
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001782 CPPCodeGenerator cg(fContext.get(), &program, this, name, &out);
Ethan Nicholas762466e2017-06-29 10:03:38 -04001783 bool result = cg.generateCode();
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001784 fSource = nullptr;
Ethan Nicholas762466e2017-06-29 10:03:38 -04001785 return result;
1786}
1787
Ethan Nicholas00543112018-07-31 09:44:36 -04001788bool Compiler::toH(Program& program, String name, OutputStream& out) {
1789 if (!this->optimize(program)) {
1790 return false;
1791 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001792 fSource = program.fSource.get();
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001793 HCodeGenerator cg(fContext.get(), &program, this, name, &out);
Ethan Nicholas762466e2017-06-29 10:03:38 -04001794 bool result = cg.generateCode();
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001795 fSource = nullptr;
Ethan Nicholas00543112018-07-31 09:44:36 -04001796 return result;
1797}
Ethan Nicholas2a479a52020-08-18 16:29:45 -04001798#endif // defined(SKSL_STANDALONE) || defined(GR_TEST_UTILS)
Ethan Nicholas00543112018-07-31 09:44:36 -04001799
Ethan Nicholas2a479a52020-08-18 16:29:45 -04001800#endif // defined(SKSL_STANDALONE) || SK_SUPPORT_GPU
Brian Osman2e29ab52019-09-20 12:19:11 -04001801
1802#if !defined(SKSL_STANDALONE) && SK_SUPPORT_GPU
Brian Osmana4b91692020-08-10 14:26:16 -04001803bool Compiler::toPipelineStage(Program& program, PipelineStageArgs* outArgs) {
1804 if (!this->optimize(program)) {
1805 return false;
1806 }
Ethan Nicholas00543112018-07-31 09:44:36 -04001807 fSource = program.fSource.get();
1808 StringStream buffer;
Brian Osman300fe1d2020-01-23 15:42:43 -05001809 PipelineStageCodeGenerator cg(fContext.get(), &program, this, &buffer, outArgs);
Ethan Nicholas00543112018-07-31 09:44:36 -04001810 bool result = cg.generateCode();
1811 fSource = nullptr;
1812 if (result) {
Brian Osman107c6662019-12-30 15:02:30 -05001813 outArgs->fCode = buffer.str();
Ethan Nicholas00543112018-07-31 09:44:36 -04001814 }
Ethan Nicholas762466e2017-06-29 10:03:38 -04001815 return result;
1816}
Brian Osmanfb32ddf2019-06-18 10:14:20 -04001817#endif
1818
Ethan Nicholas0e9401d2019-03-21 11:05:37 -04001819std::unique_ptr<ByteCode> Compiler::toByteCode(Program& program) {
Mike Klein853d4ed2020-08-20 00:41:00 +00001820#if defined(SK_ENABLE_SKSL_INTERPRETER)
Ethan Nicholas0e9401d2019-03-21 11:05:37 -04001821 if (!this->optimize(program)) {
1822 return nullptr;
1823 }
Brian Osman808f0212020-01-21 15:36:47 -05001824 fSource = program.fSource.get();
Ethan Nicholas0e9401d2019-03-21 11:05:37 -04001825 std::unique_ptr<ByteCode> result(new ByteCode());
Brian Osmanb08cc022020-04-02 11:38:40 -04001826 ByteCodeGenerator cg(fContext.get(), &program, this, result.get());
1827 bool success = cg.generateCode();
1828 fSource = nullptr;
1829 if (success) {
Ethan Nicholas0e9401d2019-03-21 11:05:37 -04001830 return result;
1831 }
Mike Klein853d4ed2020-08-20 00:41:00 +00001832#else
1833 ABORT("ByteCode interpreter not enabled");
1834#endif
Ethan Nicholas0e9401d2019-03-21 11:05:37 -04001835 return nullptr;
1836}
1837
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001838const char* Compiler::OperatorName(Token::Kind kind) {
1839 switch (kind) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001840 case Token::Kind::TK_PLUS: return "+";
1841 case Token::Kind::TK_MINUS: return "-";
1842 case Token::Kind::TK_STAR: return "*";
1843 case Token::Kind::TK_SLASH: return "/";
1844 case Token::Kind::TK_PERCENT: return "%";
1845 case Token::Kind::TK_SHL: return "<<";
1846 case Token::Kind::TK_SHR: return ">>";
1847 case Token::Kind::TK_LOGICALNOT: return "!";
1848 case Token::Kind::TK_LOGICALAND: return "&&";
1849 case Token::Kind::TK_LOGICALOR: return "||";
1850 case Token::Kind::TK_LOGICALXOR: return "^^";
1851 case Token::Kind::TK_BITWISENOT: return "~";
1852 case Token::Kind::TK_BITWISEAND: return "&";
1853 case Token::Kind::TK_BITWISEOR: return "|";
1854 case Token::Kind::TK_BITWISEXOR: return "^";
1855 case Token::Kind::TK_EQ: return "=";
1856 case Token::Kind::TK_EQEQ: return "==";
1857 case Token::Kind::TK_NEQ: return "!=";
1858 case Token::Kind::TK_LT: return "<";
1859 case Token::Kind::TK_GT: return ">";
1860 case Token::Kind::TK_LTEQ: return "<=";
1861 case Token::Kind::TK_GTEQ: return ">=";
1862 case Token::Kind::TK_PLUSEQ: return "+=";
1863 case Token::Kind::TK_MINUSEQ: return "-=";
1864 case Token::Kind::TK_STAREQ: return "*=";
1865 case Token::Kind::TK_SLASHEQ: return "/=";
1866 case Token::Kind::TK_PERCENTEQ: return "%=";
1867 case Token::Kind::TK_SHLEQ: return "<<=";
1868 case Token::Kind::TK_SHREQ: return ">>=";
1869 case Token::Kind::TK_LOGICALANDEQ: return "&&=";
1870 case Token::Kind::TK_LOGICALOREQ: return "||=";
1871 case Token::Kind::TK_LOGICALXOREQ: return "^^=";
1872 case Token::Kind::TK_BITWISEANDEQ: return "&=";
1873 case Token::Kind::TK_BITWISEOREQ: return "|=";
1874 case Token::Kind::TK_BITWISEXOREQ: return "^=";
1875 case Token::Kind::TK_PLUSPLUS: return "++";
1876 case Token::Kind::TK_MINUSMINUS: return "--";
1877 case Token::Kind::TK_COMMA: return ",";
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001878 default:
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001879 ABORT("unsupported operator: %d\n", (int) kind);
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001880 }
1881}
1882
1883
1884bool Compiler::IsAssignment(Token::Kind op) {
1885 switch (op) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001886 case Token::Kind::TK_EQ: // fall through
1887 case Token::Kind::TK_PLUSEQ: // fall through
1888 case Token::Kind::TK_MINUSEQ: // fall through
1889 case Token::Kind::TK_STAREQ: // fall through
1890 case Token::Kind::TK_SLASHEQ: // fall through
1891 case Token::Kind::TK_PERCENTEQ: // fall through
1892 case Token::Kind::TK_SHLEQ: // fall through
1893 case Token::Kind::TK_SHREQ: // fall through
1894 case Token::Kind::TK_BITWISEOREQ: // fall through
1895 case Token::Kind::TK_BITWISEXOREQ: // fall through
1896 case Token::Kind::TK_BITWISEANDEQ: // fall through
1897 case Token::Kind::TK_LOGICALOREQ: // fall through
1898 case Token::Kind::TK_LOGICALXOREQ: // fall through
1899 case Token::Kind::TK_LOGICALANDEQ:
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001900 return true;
1901 default:
1902 return false;
1903 }
1904}
1905
1906Position Compiler::position(int offset) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001907 SkASSERT(fSource);
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001908 int line = 1;
1909 int column = 1;
1910 for (int i = 0; i < offset; i++) {
1911 if ((*fSource)[i] == '\n') {
1912 ++line;
1913 column = 1;
1914 }
1915 else {
1916 ++column;
1917 }
1918 }
1919 return Position(line, column);
1920}
1921
1922void Compiler::error(int offset, String msg) {
ethannicholasb3058bd2016-07-01 08:22:01 -07001923 fErrorCount++;
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001924 Position pos = this->position(offset);
1925 fErrorText += "error: " + to_string(pos.fLine) + ": " + msg.c_str() + "\n";
ethannicholasb3058bd2016-07-01 08:22:01 -07001926}
1927
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001928String Compiler::errorText() {
Ethan Nicholas00543112018-07-31 09:44:36 -04001929 this->writeErrorCount();
1930 fErrorCount = 0;
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001931 String result = fErrorText;
ethannicholasb3058bd2016-07-01 08:22:01 -07001932 return result;
1933}
1934
1935void Compiler::writeErrorCount() {
1936 if (fErrorCount) {
1937 fErrorText += to_string(fErrorCount) + " error";
1938 if (fErrorCount > 1) {
1939 fErrorText += "s";
1940 }
1941 fErrorText += "\n";
1942 }
1943}
1944
John Stilesa6841be2020-08-06 14:11:56 -04001945} // namespace SkSL