blob: db5dc3eb3d48d0acf542cceab21f2fcd5745affd [file] [log] [blame]
ethannicholasb3058bd2016-07-01 08:22:01 -07001/*
2 * Copyright 2016 Google Inc.
3 *
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
6 */
Mike Klein6ad99092016-10-26 10:35:22 -04007
Mike Kleinc0bd9f92019-04-23 12:05:21 -05008#include "src/sksl/SkSLCompiler.h"
ethannicholasb3058bd2016-07-01 08:22:01 -07009
John Stilesfbd050b2020-08-03 13:21:46 -040010#include <memory>
John Stilesb8e010c2020-08-11 18:05:39 -040011#include <unordered_set>
John Stilesfbd050b2020-08-03 13:21:46 -040012
John Stilesb92641c2020-08-31 18:09:01 -040013#include "src/sksl/SkSLAnalysis.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050014#include "src/sksl/SkSLByteCodeGenerator.h"
15#include "src/sksl/SkSLCFGGenerator.h"
16#include "src/sksl/SkSLCPPCodeGenerator.h"
17#include "src/sksl/SkSLGLSLCodeGenerator.h"
18#include "src/sksl/SkSLHCodeGenerator.h"
19#include "src/sksl/SkSLIRGenerator.h"
20#include "src/sksl/SkSLMetalCodeGenerator.h"
21#include "src/sksl/SkSLPipelineStageCodeGenerator.h"
Ethan Nicholasc18bb512020-07-28 14:46:53 -040022#include "src/sksl/SkSLRehydrator.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050023#include "src/sksl/SkSLSPIRVCodeGenerator.h"
Brian Osmanc0243912020-02-19 15:35:26 -050024#include "src/sksl/SkSLSPIRVtoHLSL.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050025#include "src/sksl/ir/SkSLEnum.h"
26#include "src/sksl/ir/SkSLExpression.h"
27#include "src/sksl/ir/SkSLExpressionStatement.h"
28#include "src/sksl/ir/SkSLFunctionCall.h"
29#include "src/sksl/ir/SkSLIntLiteral.h"
30#include "src/sksl/ir/SkSLModifiersDeclaration.h"
31#include "src/sksl/ir/SkSLNop.h"
32#include "src/sksl/ir/SkSLSymbolTable.h"
33#include "src/sksl/ir/SkSLTernaryExpression.h"
34#include "src/sksl/ir/SkSLUnresolvedFunction.h"
35#include "src/sksl/ir/SkSLVarDeclarations.h"
ethannicholasb3058bd2016-07-01 08:22:01 -070036
Ethan Nicholasb33fa3f2020-08-06 13:00:19 -040037#include <fstream>
38
Ethan Nicholasa11035b2019-11-26 16:27:47 -050039#if !defined(SKSL_STANDALONE) & SK_SUPPORT_GPU
40#include "include/gpu/GrContextOptions.h"
41#include "src/gpu/GrShaderCaps.h"
42#endif
43
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -040044#ifdef SK_ENABLE_SPIRV_VALIDATION
45#include "spirv-tools/libspirv.hpp"
46#endif
47
Brian Osmandd496172020-08-08 08:17:18 -040048#if !SKSL_STANDALONE
Ethan Nicholasc18bb512020-07-28 14:46:53 -040049
50#include "src/sksl/generated/sksl_fp.dehydrated.sksl"
51#include "src/sksl/generated/sksl_frag.dehydrated.sksl"
52#include "src/sksl/generated/sksl_geom.dehydrated.sksl"
53#include "src/sksl/generated/sksl_gpu.dehydrated.sksl"
54#include "src/sksl/generated/sksl_interp.dehydrated.sksl"
55#include "src/sksl/generated/sksl_pipeline.dehydrated.sksl"
56#include "src/sksl/generated/sksl_vert.dehydrated.sksl"
57
58#else
59
Brian Osmandd496172020-08-08 08:17:18 -040060// GN generates or copies all of these files to the skslc executable directory
61static const char SKSL_GPU_INCLUDE[] = "sksl_gpu.sksl";
62static const char SKSL_INTERP_INCLUDE[] = "sksl_interp.sksl";
63static const char SKSL_VERT_INCLUDE[] = "sksl_vert.sksl";
64static const char SKSL_FRAG_INCLUDE[] = "sksl_frag.sksl";
65static const char SKSL_GEOM_INCLUDE[] = "sksl_geom.sksl";
66static const char SKSL_FP_INCLUDE[] = "sksl_fp.sksl";
67static const char SKSL_PIPELINE_INCLUDE[] = "sksl_pipeline.sksl";
Ethan Nicholasc18bb512020-07-28 14:46:53 -040068
69#endif
Ethan Nicholas0d997662019-04-08 09:46:01 -040070
ethannicholasb3058bd2016-07-01 08:22:01 -070071namespace SkSL {
72
Ethan Nicholasdb80f692019-11-22 14:06:12 -050073static void grab_intrinsics(std::vector<std::unique_ptr<ProgramElement>>* src,
John Stiles810c8cf2020-08-26 19:46:27 -040074 IRIntrinsicMap* target) {
Brian Osman08f986d2020-05-13 17:06:46 -040075 for (auto iter = src->begin(); iter != src->end(); ) {
76 std::unique_ptr<ProgramElement>& element = *iter;
Ethan Nicholase6592142020-09-08 10:22:09 -040077 switch (element->kind()) {
78 case ProgramElement::Kind::kFunction: {
John Stiles3dc0da62020-08-19 17:48:31 -040079 FunctionDefinition& f = element->as<FunctionDefinition>();
Brian Osman08f986d2020-05-13 17:06:46 -040080 SkASSERT(f.fDeclaration.fBuiltin);
Ethan Nicholasc18bb512020-07-28 14:46:53 -040081 String key = f.fDeclaration.description();
Brian Osman08f986d2020-05-13 17:06:46 -040082 SkASSERT(target->find(key) == target->end());
John Stiles810c8cf2020-08-26 19:46:27 -040083 (*target)[key] = IRIntrinsic{std::move(element), /*fAlreadyIncluded=*/false};
Brian Osman08f986d2020-05-13 17:06:46 -040084 iter = src->erase(iter);
Ethan Nicholasdb80f692019-11-22 14:06:12 -050085 break;
86 }
Ethan Nicholase6592142020-09-08 10:22:09 -040087 case ProgramElement::Kind::kEnum: {
John Stiles3dc0da62020-08-19 17:48:31 -040088 Enum& e = element->as<Enum>();
Ethan Nicholasdb80f692019-11-22 14:06:12 -050089 StringFragment name = e.fTypeName;
90 SkASSERT(target->find(name) == target->end());
John Stiles810c8cf2020-08-26 19:46:27 -040091 (*target)[name] = IRIntrinsic{std::move(element), /*fAlreadyIncluded=*/false};
Brian Osman08f986d2020-05-13 17:06:46 -040092 iter = src->erase(iter);
Ethan Nicholasdb80f692019-11-22 14:06:12 -050093 break;
94 }
95 default:
96 printf("unsupported include file element\n");
97 SkASSERT(false);
98 }
99 }
100}
101
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -0400102Compiler::Compiler(Flags flags)
John Stiles810c8cf2020-08-26 19:46:27 -0400103: fGPUIntrinsics(std::make_unique<IRIntrinsicMap>())
104, fInterpreterIntrinsics(std::make_unique<IRIntrinsicMap>())
105, fFlags(flags)
106, fContext(std::make_shared<Context>())
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -0400107, fErrorCount(0) {
Brian Osmaneac49832020-09-18 11:49:22 -0400108 fRootSymbolTable = std::make_shared<SymbolTable>(this);
John Stiles21d77782020-09-18 14:01:34 -0400109 fIRGenerator = std::make_unique<IRGenerator>(fContext.get(), fRootSymbolTable, *this);
Brian Osmaneac49832020-09-18 11:49:22 -0400110 #define ADD_TYPE(t) fRootSymbolTable->addWithoutOwnership(fContext->f ## t ## _Type->fName, \
111 fContext->f ## t ## _Type.get())
ethannicholasb3058bd2016-07-01 08:22:01 -0700112 ADD_TYPE(Void);
113 ADD_TYPE(Float);
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400114 ADD_TYPE(Float2);
115 ADD_TYPE(Float3);
116 ADD_TYPE(Float4);
Ethan Nicholasdcba08e2017-08-02 10:52:54 -0400117 ADD_TYPE(Half);
118 ADD_TYPE(Half2);
119 ADD_TYPE(Half3);
120 ADD_TYPE(Half4);
ethannicholasb3058bd2016-07-01 08:22:01 -0700121 ADD_TYPE(Int);
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400122 ADD_TYPE(Int2);
123 ADD_TYPE(Int3);
124 ADD_TYPE(Int4);
ethannicholasb3058bd2016-07-01 08:22:01 -0700125 ADD_TYPE(UInt);
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400126 ADD_TYPE(UInt2);
127 ADD_TYPE(UInt3);
128 ADD_TYPE(UInt4);
Ethan Nicholasdcba08e2017-08-02 10:52:54 -0400129 ADD_TYPE(Short);
130 ADD_TYPE(Short2);
131 ADD_TYPE(Short3);
132 ADD_TYPE(Short4);
133 ADD_TYPE(UShort);
134 ADD_TYPE(UShort2);
135 ADD_TYPE(UShort3);
136 ADD_TYPE(UShort4);
Ruiqi Maob609e6d2018-07-17 10:19:38 -0400137 ADD_TYPE(Byte);
138 ADD_TYPE(Byte2);
139 ADD_TYPE(Byte3);
140 ADD_TYPE(Byte4);
141 ADD_TYPE(UByte);
142 ADD_TYPE(UByte2);
143 ADD_TYPE(UByte3);
144 ADD_TYPE(UByte4);
ethannicholasb3058bd2016-07-01 08:22:01 -0700145 ADD_TYPE(Bool);
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400146 ADD_TYPE(Bool2);
147 ADD_TYPE(Bool3);
148 ADD_TYPE(Bool4);
149 ADD_TYPE(Float2x2);
150 ADD_TYPE(Float2x3);
151 ADD_TYPE(Float2x4);
152 ADD_TYPE(Float3x2);
153 ADD_TYPE(Float3x3);
154 ADD_TYPE(Float3x4);
155 ADD_TYPE(Float4x2);
156 ADD_TYPE(Float4x3);
157 ADD_TYPE(Float4x4);
Ethan Nicholasdcba08e2017-08-02 10:52:54 -0400158 ADD_TYPE(Half2x2);
159 ADD_TYPE(Half2x3);
160 ADD_TYPE(Half2x4);
161 ADD_TYPE(Half3x2);
162 ADD_TYPE(Half3x3);
163 ADD_TYPE(Half3x4);
164 ADD_TYPE(Half4x2);
165 ADD_TYPE(Half4x3);
166 ADD_TYPE(Half4x4);
ethannicholasb3058bd2016-07-01 08:22:01 -0700167 ADD_TYPE(GenType);
Ethan Nicholasdcba08e2017-08-02 10:52:54 -0400168 ADD_TYPE(GenHType);
ethannicholasb3058bd2016-07-01 08:22:01 -0700169 ADD_TYPE(GenIType);
170 ADD_TYPE(GenUType);
171 ADD_TYPE(GenBType);
172 ADD_TYPE(Mat);
173 ADD_TYPE(Vec);
174 ADD_TYPE(GVec);
175 ADD_TYPE(GVec2);
176 ADD_TYPE(GVec3);
177 ADD_TYPE(GVec4);
Ethan Nicholasdcba08e2017-08-02 10:52:54 -0400178 ADD_TYPE(HVec);
ethannicholasb3058bd2016-07-01 08:22:01 -0700179 ADD_TYPE(IVec);
180 ADD_TYPE(UVec);
Ethan Nicholasdcba08e2017-08-02 10:52:54 -0400181 ADD_TYPE(SVec);
182 ADD_TYPE(USVec);
Ruiqi Maob609e6d2018-07-17 10:19:38 -0400183 ADD_TYPE(ByteVec);
184 ADD_TYPE(UByteVec);
ethannicholasb3058bd2016-07-01 08:22:01 -0700185 ADD_TYPE(BVec);
186
187 ADD_TYPE(Sampler1D);
188 ADD_TYPE(Sampler2D);
189 ADD_TYPE(Sampler3D);
ethannicholas5961bc92016-10-12 06:39:56 -0700190 ADD_TYPE(SamplerExternalOES);
ethannicholasb3058bd2016-07-01 08:22:01 -0700191 ADD_TYPE(SamplerCube);
192 ADD_TYPE(Sampler2DRect);
193 ADD_TYPE(Sampler1DArray);
194 ADD_TYPE(Sampler2DArray);
195 ADD_TYPE(SamplerCubeArray);
196 ADD_TYPE(SamplerBuffer);
197 ADD_TYPE(Sampler2DMS);
198 ADD_TYPE(Sampler2DMSArray);
199
Brian Salomonbf7b6202016-11-11 16:08:03 -0500200 ADD_TYPE(ISampler2D);
201
Brian Salomon2a51de82016-11-16 12:06:01 -0500202 ADD_TYPE(Image2D);
203 ADD_TYPE(IImage2D);
204
Greg Daniel64773e62016-11-22 09:44:03 -0500205 ADD_TYPE(SubpassInput);
206 ADD_TYPE(SubpassInputMS);
207
ethannicholasb3058bd2016-07-01 08:22:01 -0700208 ADD_TYPE(GSampler1D);
209 ADD_TYPE(GSampler2D);
210 ADD_TYPE(GSampler3D);
211 ADD_TYPE(GSamplerCube);
212 ADD_TYPE(GSampler2DRect);
213 ADD_TYPE(GSampler1DArray);
214 ADD_TYPE(GSampler2DArray);
215 ADD_TYPE(GSamplerCubeArray);
216 ADD_TYPE(GSamplerBuffer);
217 ADD_TYPE(GSampler2DMS);
218 ADD_TYPE(GSampler2DMSArray);
219
220 ADD_TYPE(Sampler1DShadow);
221 ADD_TYPE(Sampler2DShadow);
222 ADD_TYPE(SamplerCubeShadow);
223 ADD_TYPE(Sampler2DRectShadow);
224 ADD_TYPE(Sampler1DArrayShadow);
225 ADD_TYPE(Sampler2DArrayShadow);
226 ADD_TYPE(SamplerCubeArrayShadow);
227 ADD_TYPE(GSampler2DArrayShadow);
228 ADD_TYPE(GSamplerCubeArrayShadow);
Ethan Nicholasc9472af2017-10-10 16:30:21 -0400229 ADD_TYPE(FragmentProcessor);
Stephen Whiteff5d7a22019-07-26 17:42:06 -0400230 ADD_TYPE(Sampler);
231 ADD_TYPE(Texture2D);
ethannicholasb3058bd2016-07-01 08:22:01 -0700232
Brian Osman28590d52020-03-23 16:59:08 -0400233 StringFragment fpAliasName("shader");
Brian Osmaneac49832020-09-18 11:49:22 -0400234 fRootSymbolTable->addWithoutOwnership(fpAliasName, fContext->fFragmentProcessor_Type.get());
Brian Osman28590d52020-03-23 16:59:08 -0400235
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700236 StringFragment skCapsName("sk_Caps");
Brian Osmaneac49832020-09-18 11:49:22 -0400237 fRootSymbolTable->add(
John Stiles311dd9d2020-08-13 17:09:29 -0400238 skCapsName,
239 std::make_unique<Variable>(/*offset=*/-1, Modifiers(), skCapsName,
Ethan Nicholas30d30222020-09-11 12:27:26 -0400240 fContext->fSkCaps_Type.get(), Variable::kGlobal_Storage));
Ethan Nicholas3605ace2016-11-21 15:59:48 -0500241
John Stiles810c8cf2020-08-26 19:46:27 -0400242 fIRGenerator->fIntrinsics = fGPUIntrinsics.get();
Ethan Nicholasdb80f692019-11-22 14:06:12 -0500243 std::vector<std::unique_ptr<ProgramElement>> gpuIntrinsics;
Brian Osmandd496172020-08-08 08:17:18 -0400244#if SKSL_STANDALONE
Brian Osmaneac49832020-09-18 11:49:22 -0400245 this->processIncludeFile(Program::kFragment_Kind, SKSL_GPU_INCLUDE, fRootSymbolTable,
246 &gpuIntrinsics, &fGpuSymbolTable);
Ethan Nicholasb33fa3f2020-08-06 13:00:19 -0400247 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 {
Brian Osmaneac49832020-09-18 11:49:22 -0400253 Rehydrator rehydrator(fContext.get(), fRootSymbolTable, this, SKSL_INCLUDE_sksl_gpu,
254 SKSL_INCLUDE_sksl_gpu_LENGTH);
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400255 fGpuSymbolTable = rehydrator.symbolTable();
256 gpuIntrinsics = rehydrator.elements();
257 }
258 {
259 Rehydrator rehydrator(fContext.get(), fGpuSymbolTable, this, SKSL_INCLUDE_sksl_vert,
Brian Osmaneac49832020-09-18 11:49:22 -0400260 SKSL_INCLUDE_sksl_vert_LENGTH);
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400261 fVertexSymbolTable = rehydrator.symbolTable();
262 fVertexInclude = rehydrator.elements();
263 }
264 {
265 Rehydrator rehydrator(fContext.get(), fGpuSymbolTable, this, SKSL_INCLUDE_sksl_frag,
Brian Osmaneac49832020-09-18 11:49:22 -0400266 SKSL_INCLUDE_sksl_frag_LENGTH);
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400267 fFragmentSymbolTable = rehydrator.symbolTable();
268 fFragmentInclude = rehydrator.elements();
269 }
270#endif
John Stiles810c8cf2020-08-26 19:46:27 -0400271 grab_intrinsics(&gpuIntrinsics, fGPUIntrinsics.get());
ethannicholasb3058bd2016-07-01 08:22:01 -0700272}
273
John Stiles656427a2020-08-27 15:26:26 -0400274Compiler::~Compiler() {}
ethannicholasb3058bd2016-07-01 08:22:01 -0700275
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400276void Compiler::loadGeometryIntrinsics() {
277 if (fGeometrySymbolTable) {
278 return;
279 }
Brian Osmandd496172020-08-08 08:17:18 -0400280 #if !SKSL_STANDALONE
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400281 {
282 Rehydrator rehydrator(fContext.get(), fGpuSymbolTable, this, SKSL_INCLUDE_sksl_geom,
283 SKSL_INCLUDE_sksl_geom_LENGTH);
284 fGeometrySymbolTable = rehydrator.symbolTable();
285 fGeometryInclude = rehydrator.elements();
286 }
287 #else
Ethan Nicholasb33fa3f2020-08-06 13:00:19 -0400288 this->processIncludeFile(Program::kGeometry_Kind, SKSL_GEOM_INCLUDE, fGpuSymbolTable,
289 &fGeometryInclude, &fGeometrySymbolTable);
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400290 #endif
291}
292
293void Compiler::loadPipelineIntrinsics() {
294 if (fPipelineSymbolTable) {
295 return;
296 }
Brian Osmandd496172020-08-08 08:17:18 -0400297 #if !SKSL_STANDALONE
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400298 {
299 Rehydrator rehydrator(fContext.get(), fGpuSymbolTable, this,
300 SKSL_INCLUDE_sksl_pipeline,
301 SKSL_INCLUDE_sksl_pipeline_LENGTH);
302 fPipelineSymbolTable = rehydrator.symbolTable();
303 fPipelineInclude = rehydrator.elements();
304 }
305 #else
306 this->processIncludeFile(Program::kPipelineStage_Kind, SKSL_PIPELINE_INCLUDE,
Ethan Nicholasb33fa3f2020-08-06 13:00:19 -0400307 fGpuSymbolTable, &fPipelineInclude, &fPipelineSymbolTable);
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400308 #endif
309}
310
311void Compiler::loadInterpreterIntrinsics() {
312 if (fInterpreterSymbolTable) {
313 return;
314 }
Brian Osmaneac49832020-09-18 11:49:22 -0400315 std::vector<std::unique_ptr<ProgramElement>> interpIntrinsics;
Brian Osmandd496172020-08-08 08:17:18 -0400316 #if !SKSL_STANDALONE
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400317 {
Brian Osmaneac49832020-09-18 11:49:22 -0400318 Rehydrator rehydrator(fContext.get(), fRootSymbolTable, this,
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400319 SKSL_INCLUDE_sksl_interp,
320 SKSL_INCLUDE_sksl_interp_LENGTH);
321 fInterpreterSymbolTable = rehydrator.symbolTable();
Brian Osmaneac49832020-09-18 11:49:22 -0400322 interpIntrinsics = rehydrator.elements();
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400323 }
324 #else
325 this->processIncludeFile(Program::kGeneric_Kind, SKSL_INTERP_INCLUDE,
Brian Osmaneac49832020-09-18 11:49:22 -0400326 fIRGenerator->fSymbolTable, &interpIntrinsics,
Ethan Nicholasb33fa3f2020-08-06 13:00:19 -0400327 &fInterpreterSymbolTable);
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400328 #endif
Brian Osmaneac49832020-09-18 11:49:22 -0400329 grab_intrinsics(&interpIntrinsics, fInterpreterIntrinsics.get());
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400330}
331
Ethan Nicholasb33fa3f2020-08-06 13:00:19 -0400332void Compiler::processIncludeFile(Program::Kind kind, const char* path,
Ethan Nicholas8da1e652019-05-24 11:01:59 -0400333 std::shared_ptr<SymbolTable> base,
334 std::vector<std::unique_ptr<ProgramElement>>* outElements,
335 std::shared_ptr<SymbolTable>* outSymbolTable) {
Ethan Nicholasb33fa3f2020-08-06 13:00:19 -0400336 std::ifstream in(path);
337 std::string stdText{std::istreambuf_iterator<char>(in),
338 std::istreambuf_iterator<char>()};
339 if (in.rdstate()) {
340 printf("error reading %s\n", path);
341 abort();
342 }
343 if (!base) {
344 base = fIRGenerator->fSymbolTable;
345 }
346 SkASSERT(base);
347 const String* source = base->takeOwnershipOfString(std::make_unique<String>(stdText.c_str()));
348 fSource = source;
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400349 std::shared_ptr<SymbolTable> old = fIRGenerator->fSymbolTable;
350 if (base) {
351 fIRGenerator->fSymbolTable = std::move(base);
352 }
Ethan Nicholas8da1e652019-05-24 11:01:59 -0400353 Program::Settings settings;
John Stiles910845f2020-09-18 15:41:07 -0400354 settings.fInline = false;
Ethan Nicholasa11035b2019-11-26 16:27:47 -0500355#if !defined(SKSL_STANDALONE) & SK_SUPPORT_GPU
356 GrContextOptions opts;
357 GrShaderCaps caps(opts);
358 settings.fCaps = &caps;
359#endif
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400360 fIRGenerator->start(&settings, nullptr, true);
Ethan Nicholasb33fa3f2020-08-06 13:00:19 -0400361 fIRGenerator->convertProgram(kind, source->c_str(), source->length(), outElements);
Ethan Nicholas8da1e652019-05-24 11:01:59 -0400362 if (this->fErrorCount) {
363 printf("Unexpected errors: %s\n", this->fErrorText.c_str());
364 }
365 SkASSERT(!fErrorCount);
Ethan Nicholas8da1e652019-05-24 11:01:59 -0400366 *outSymbolTable = fIRGenerator->fSymbolTable;
Ethan Nicholasa11035b2019-11-26 16:27:47 -0500367#ifdef SK_DEBUG
368 fSource = nullptr;
369#endif
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400370 fIRGenerator->fSymbolTable = std::move(old);
Ethan Nicholas8da1e652019-05-24 11:01:59 -0400371}
372
ethannicholas22f939e2016-10-13 13:25:34 -0700373// add the definition created by assigning to the lvalue to the definition set
Ethan Nicholas86a43402017-01-19 13:32:00 -0500374void Compiler::addDefinition(const Expression* lvalue, std::unique_ptr<Expression>* expr,
375 DefinitionMap* definitions) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400376 switch (lvalue->kind()) {
377 case Expression::Kind::kVariableReference: {
John Stilesa5a97b42020-08-18 11:19:07 -0400378 const Variable& var = lvalue->as<VariableReference>().fVariable;
ethannicholas22f939e2016-10-13 13:25:34 -0700379 if (var.fStorage == Variable::kLocal_Storage) {
380 (*definitions)[&var] = expr;
381 }
382 break;
383 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400384 case Expression::Kind::kSwizzle:
ethannicholas22f939e2016-10-13 13:25:34 -0700385 // We consider the variable written to as long as at least some of its components have
386 // been written to. This will lead to some false negatives (we won't catch it if you
387 // write to foo.x and then read foo.y), but being stricter could lead to false positives
Mike Klein6ad99092016-10-26 10:35:22 -0400388 // (we write to foo.x, and then pass foo to a function which happens to only read foo.x,
389 // 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 -0700390 // more complicated whole-program analysis. This is probably good enough.
John Stilesa5a97b42020-08-18 11:19:07 -0400391 this->addDefinition(lvalue->as<Swizzle>().fBase.get(),
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400392 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
ethannicholas22f939e2016-10-13 13:25:34 -0700393 definitions);
394 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400395 case Expression::Kind::kIndex:
ethannicholas22f939e2016-10-13 13:25:34 -0700396 // see comments in Swizzle
John Stilesa5a97b42020-08-18 11:19:07 -0400397 this->addDefinition(lvalue->as<IndexExpression>().fBase.get(),
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400398 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
ethannicholas22f939e2016-10-13 13:25:34 -0700399 definitions);
400 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400401 case Expression::Kind::kFieldAccess:
ethannicholas22f939e2016-10-13 13:25:34 -0700402 // see comments in Swizzle
John Stilesa5a97b42020-08-18 11:19:07 -0400403 this->addDefinition(lvalue->as<FieldAccess>().fBase.get(),
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400404 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
ethannicholas22f939e2016-10-13 13:25:34 -0700405 definitions);
406 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400407 case Expression::Kind::kTernary:
Ethan Nicholasa583b812018-01-18 13:32:11 -0500408 // To simplify analysis, we just pretend that we write to both sides of the ternary.
409 // This allows for false positives (meaning we fail to detect that a variable might not
410 // have been assigned), but is preferable to false negatives.
John Stilesa5a97b42020-08-18 11:19:07 -0400411 this->addDefinition(lvalue->as<TernaryExpression>().fIfTrue.get(),
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400412 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
Ethan Nicholasa583b812018-01-18 13:32:11 -0500413 definitions);
John Stilesa5a97b42020-08-18 11:19:07 -0400414 this->addDefinition(lvalue->as<TernaryExpression>().fIfFalse.get(),
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400415 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
Ethan Nicholasa583b812018-01-18 13:32:11 -0500416 definitions);
417 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400418 case Expression::Kind::kExternalValue:
Ethan Nicholas91164d12019-05-15 15:29:54 -0400419 break;
ethannicholas22f939e2016-10-13 13:25:34 -0700420 default:
421 // not an lvalue, can't happen
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400422 SkASSERT(false);
ethannicholas22f939e2016-10-13 13:25:34 -0700423 }
424}
425
426// add local variables defined by this node to the set
Mike Klein6ad99092016-10-26 10:35:22 -0400427void Compiler::addDefinitions(const BasicBlock::Node& node,
Ethan Nicholas86a43402017-01-19 13:32:00 -0500428 DefinitionMap* definitions) {
ethannicholas22f939e2016-10-13 13:25:34 -0700429 switch (node.fKind) {
430 case BasicBlock::Node::kExpression_Kind: {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400431 SkASSERT(node.expression());
John Stilesa5a97b42020-08-18 11:19:07 -0400432 Expression* expr = node.expression()->get();
Ethan Nicholase6592142020-09-08 10:22:09 -0400433 switch (expr->kind()) {
434 case Expression::Kind::kBinary: {
John Stilesa5a97b42020-08-18 11:19:07 -0400435 BinaryExpression* b = &expr->as<BinaryExpression>();
Ethan Nicholasbf66ffb2020-09-16 22:05:10 +0000436 if (b->fOperator == Token::Kind::TK_EQ) {
437 this->addDefinition(b->fLeft.get(), &b->fRight, definitions);
438 } else if (Compiler::IsAssignment(b->fOperator)) {
Ethan Nicholas86a43402017-01-19 13:32:00 -0500439 this->addDefinition(
Ethan Nicholasbf66ffb2020-09-16 22:05:10 +0000440 b->fLeft.get(),
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400441 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
442 definitions);
Ethan Nicholas86a43402017-01-19 13:32:00 -0500443
444 }
445 break;
ethannicholas22f939e2016-10-13 13:25:34 -0700446 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400447 case Expression::Kind::kFunctionCall: {
John Stilesa5a97b42020-08-18 11:19:07 -0400448 const FunctionCall& c = expr->as<FunctionCall>();
Ethan Nicholasc6a19f12018-03-29 16:46:56 -0400449 for (size_t i = 0; i < c.fFunction.fParameters.size(); ++i) {
450 if (c.fFunction.fParameters[i]->fModifiers.fFlags & Modifiers::kOut_Flag) {
451 this->addDefinition(
452 c.fArguments[i].get(),
453 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
454 definitions);
455 }
456 }
457 break;
458 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400459 case Expression::Kind::kPrefix: {
John Stilesa5a97b42020-08-18 11:19:07 -0400460 const PrefixExpression* p = &expr->as<PrefixExpression>();
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400461 if (p->fOperator == Token::Kind::TK_MINUSMINUS ||
462 p->fOperator == Token::Kind::TK_PLUSPLUS) {
Ethan Nicholas86a43402017-01-19 13:32:00 -0500463 this->addDefinition(
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400464 p->fOperand.get(),
465 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
466 definitions);
Ethan Nicholas86a43402017-01-19 13:32:00 -0500467 }
468 break;
469 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400470 case Expression::Kind::kPostfix: {
John Stilesa5a97b42020-08-18 11:19:07 -0400471 const PostfixExpression* p = &expr->as<PostfixExpression>();
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400472 if (p->fOperator == Token::Kind::TK_MINUSMINUS ||
473 p->fOperator == Token::Kind::TK_PLUSPLUS) {
Ethan Nicholas86a43402017-01-19 13:32:00 -0500474 this->addDefinition(
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400475 p->fOperand.get(),
476 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
477 definitions);
Ethan Nicholas86a43402017-01-19 13:32:00 -0500478 }
479 break;
480 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400481 case Expression::Kind::kVariableReference: {
John Stilesa5a97b42020-08-18 11:19:07 -0400482 const VariableReference* v = &expr->as<VariableReference>();
Ethan Nicholascb670962017-04-20 19:31:52 -0400483 if (v->fRefKind != VariableReference::kRead_RefKind) {
484 this->addDefinition(
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400485 v,
486 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
487 definitions);
Ethan Nicholascb670962017-04-20 19:31:52 -0400488 }
John Stiles30212b72020-06-11 17:55:07 -0400489 break;
Ethan Nicholascb670962017-04-20 19:31:52 -0400490 }
Ethan Nicholas86a43402017-01-19 13:32:00 -0500491 default:
492 break;
ethannicholas22f939e2016-10-13 13:25:34 -0700493 }
494 break;
495 }
496 case BasicBlock::Node::kStatement_Kind: {
John Stilesa5a97b42020-08-18 11:19:07 -0400497 Statement* stmt = node.statement()->get();
Ethan Nicholase6592142020-09-08 10:22:09 -0400498 if (stmt->kind() == Statement::Kind::kVarDeclaration) {
John Stilesa5a97b42020-08-18 11:19:07 -0400499 VarDeclaration& vd = stmt->as<VarDeclaration>();
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000500 if (vd.fValue) {
501 (*definitions)[vd.fVar] = &vd.fValue;
ethannicholas22f939e2016-10-13 13:25:34 -0700502 }
503 }
504 break;
505 }
506 }
507}
508
509void Compiler::scanCFG(CFG* cfg, BlockId blockId, std::set<BlockId>* workList) {
510 BasicBlock& block = cfg->fBlocks[blockId];
511
512 // compute definitions after this block
Ethan Nicholas86a43402017-01-19 13:32:00 -0500513 DefinitionMap after = block.fBefore;
ethannicholas22f939e2016-10-13 13:25:34 -0700514 for (const BasicBlock::Node& n : block.fNodes) {
515 this->addDefinitions(n, &after);
516 }
517
518 // propagate definitions to exits
519 for (BlockId exitId : block.fExits) {
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400520 if (exitId == blockId) {
521 continue;
522 }
ethannicholas22f939e2016-10-13 13:25:34 -0700523 BasicBlock& exit = cfg->fBlocks[exitId];
524 for (const auto& pair : after) {
Ethan Nicholas86a43402017-01-19 13:32:00 -0500525 std::unique_ptr<Expression>* e1 = pair.second;
526 auto found = exit.fBefore.find(pair.first);
527 if (found == exit.fBefore.end()) {
528 // exit has no definition for it, just copy it
529 workList->insert(exitId);
ethannicholas22f939e2016-10-13 13:25:34 -0700530 exit.fBefore[pair.first] = e1;
531 } else {
Ethan Nicholas86a43402017-01-19 13:32:00 -0500532 // exit has a (possibly different) value already defined
533 std::unique_ptr<Expression>* e2 = exit.fBefore[pair.first];
ethannicholas22f939e2016-10-13 13:25:34 -0700534 if (e1 != e2) {
535 // definition has changed, merge and add exit block to worklist
536 workList->insert(exitId);
Ethan Nicholasaf197692017-02-27 13:26:45 -0500537 if (e1 && e2) {
538 exit.fBefore[pair.first] =
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400539 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression;
Ethan Nicholasaf197692017-02-27 13:26:45 -0500540 } else {
541 exit.fBefore[pair.first] = nullptr;
542 }
ethannicholas22f939e2016-10-13 13:25:34 -0700543 }
544 }
545 }
546 }
547}
548
549// returns a map which maps all local variables in the function to null, indicating that their value
550// is initially unknown
Ethan Nicholas86a43402017-01-19 13:32:00 -0500551static DefinitionMap compute_start_state(const CFG& cfg) {
552 DefinitionMap result;
Mike Klein6ad99092016-10-26 10:35:22 -0400553 for (const auto& block : cfg.fBlocks) {
554 for (const auto& node : block.fNodes) {
ethannicholas22f939e2016-10-13 13:25:34 -0700555 if (node.fKind == BasicBlock::Node::kStatement_Kind) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400556 SkASSERT(node.statement());
Ethan Nicholascb670962017-04-20 19:31:52 -0400557 const Statement* s = node.statement()->get();
Ethan Nicholase6592142020-09-08 10:22:09 -0400558 if (s->kind() == Statement::Kind::kVarDeclarations) {
John Stilesa5a97b42020-08-18 11:19:07 -0400559 const VarDeclarationsStatement* vd = &s->as<VarDeclarationsStatement>();
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000560 for (const auto& decl : vd->fDeclaration->fVars) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400561 if (decl->kind() == Statement::Kind::kVarDeclaration) {
John Stilesa5a97b42020-08-18 11:19:07 -0400562 result[decl->as<VarDeclaration>().fVar] = nullptr;
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000563 }
Mike Klein6ad99092016-10-26 10:35:22 -0400564 }
ethannicholas22f939e2016-10-13 13:25:34 -0700565 }
566 }
567 }
568 }
569 return result;
570}
571
Ethan Nicholascb670962017-04-20 19:31:52 -0400572/**
573 * Returns true if assigning to this lvalue has no effect.
574 */
575static bool is_dead(const Expression& lvalue) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400576 switch (lvalue.kind()) {
577 case Expression::Kind::kVariableReference:
John Stilesa5a97b42020-08-18 11:19:07 -0400578 return lvalue.as<VariableReference>().fVariable.dead();
Ethan Nicholase6592142020-09-08 10:22:09 -0400579 case Expression::Kind::kSwizzle:
John Stilesa5a97b42020-08-18 11:19:07 -0400580 return is_dead(*lvalue.as<Swizzle>().fBase);
Ethan Nicholase6592142020-09-08 10:22:09 -0400581 case Expression::Kind::kFieldAccess:
John Stilesa5a97b42020-08-18 11:19:07 -0400582 return is_dead(*lvalue.as<FieldAccess>().fBase);
Ethan Nicholase6592142020-09-08 10:22:09 -0400583 case Expression::Kind::kIndex: {
John Stilesa5a97b42020-08-18 11:19:07 -0400584 const IndexExpression& idx = lvalue.as<IndexExpression>();
Ethan Nicholas2a099da2020-01-02 14:40:54 -0500585 return is_dead(*idx.fBase) &&
586 !idx.fIndex->hasProperty(Expression::Property::kSideEffects);
Ethan Nicholascb670962017-04-20 19:31:52 -0400587 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400588 case Expression::Kind::kTernary: {
John Stilesa5a97b42020-08-18 11:19:07 -0400589 const TernaryExpression& t = lvalue.as<TernaryExpression>();
Ethan Nicholasa583b812018-01-18 13:32:11 -0500590 return !t.fTest->hasSideEffects() && is_dead(*t.fIfTrue) && is_dead(*t.fIfFalse);
591 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400592 case Expression::Kind::kExternalValue:
Ethan Nicholas91164d12019-05-15 15:29:54 -0400593 return false;
Ethan Nicholascb670962017-04-20 19:31:52 -0400594 default:
Ethan Nicholas2a099da2020-01-02 14:40:54 -0500595#ifdef SK_DEBUG
Ethan Nicholascb670962017-04-20 19:31:52 -0400596 ABORT("invalid lvalue: %s\n", lvalue.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -0500597#endif
598 return false;
Ethan Nicholascb670962017-04-20 19:31:52 -0400599 }
600}
ethannicholas22f939e2016-10-13 13:25:34 -0700601
Ethan Nicholascb670962017-04-20 19:31:52 -0400602/**
603 * Returns true if this is an assignment which can be collapsed down to just the right hand side due
604 * to a dead target and lack of side effects on the left hand side.
605 */
606static bool dead_assignment(const BinaryExpression& b) {
Ethan Nicholasbf66ffb2020-09-16 22:05:10 +0000607 if (!Compiler::IsAssignment(b.fOperator)) {
Ethan Nicholascb670962017-04-20 19:31:52 -0400608 return false;
609 }
Ethan Nicholasbf66ffb2020-09-16 22:05:10 +0000610 return is_dead(*b.fLeft);
Ethan Nicholascb670962017-04-20 19:31:52 -0400611}
612
613void Compiler::computeDataFlow(CFG* cfg) {
614 cfg->fBlocks[cfg->fStart].fBefore = compute_start_state(*cfg);
ethannicholas22f939e2016-10-13 13:25:34 -0700615 std::set<BlockId> workList;
Ethan Nicholascb670962017-04-20 19:31:52 -0400616 for (BlockId i = 0; i < cfg->fBlocks.size(); i++) {
ethannicholas22f939e2016-10-13 13:25:34 -0700617 workList.insert(i);
618 }
619 while (workList.size()) {
620 BlockId next = *workList.begin();
621 workList.erase(workList.begin());
Ethan Nicholascb670962017-04-20 19:31:52 -0400622 this->scanCFG(cfg, next, &workList);
ethannicholas22f939e2016-10-13 13:25:34 -0700623 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400624}
625
626/**
627 * Attempts to replace the expression pointed to by iter with a new one (in both the CFG and the
628 * IR). If the expression can be cleanly removed, returns true and updates the iterator to point to
629 * the newly-inserted element. Otherwise updates only the IR and returns false (and the CFG will
630 * need to be regenerated).
631 */
John Stilesafbf8992020-08-18 10:08:21 -0400632static bool try_replace_expression(BasicBlock* b,
633 std::vector<BasicBlock::Node>::iterator* iter,
634 std::unique_ptr<Expression>* newExpression) {
Ethan Nicholascb670962017-04-20 19:31:52 -0400635 std::unique_ptr<Expression>* target = (*iter)->expression();
636 if (!b->tryRemoveExpression(iter)) {
637 *target = std::move(*newExpression);
638 return false;
639 }
640 *target = std::move(*newExpression);
641 return b->tryInsertExpression(iter, target);
642}
643
644/**
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400645 * Returns true if the expression is a constant numeric literal with the specified value, or a
646 * constant vector with all elements equal to the specified value.
Ethan Nicholascb670962017-04-20 19:31:52 -0400647 */
John Stiles9d944232020-08-19 09:56:49 -0400648template <typename T = double>
649static bool is_constant(const Expression& expr, T value) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400650 switch (expr.kind()) {
651 case Expression::Kind::kIntLiteral:
John Stiles81365af2020-08-18 09:24:00 -0400652 return expr.as<IntLiteral>().fValue == value;
John Stiles9d944232020-08-19 09:56:49 -0400653
Ethan Nicholase6592142020-09-08 10:22:09 -0400654 case Expression::Kind::kFloatLiteral:
John Stiles81365af2020-08-18 09:24:00 -0400655 return expr.as<FloatLiteral>().fValue == value;
John Stiles9d944232020-08-19 09:56:49 -0400656
Ethan Nicholase6592142020-09-08 10:22:09 -0400657 case Expression::Kind::kConstructor: {
John Stiles9d944232020-08-19 09:56:49 -0400658 const Constructor& constructor = expr.as<Constructor>();
659 if (constructor.isCompileTimeConstant()) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400660 const Type& constructorType = constructor.type();
661 bool isFloat = constructorType.columns() > 1
662 ? constructorType.componentType().isFloat()
663 : constructorType.isFloat();
664 switch (constructorType.typeKind()) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400665 case Type::TypeKind::kVector:
Ethan Nicholas30d30222020-09-11 12:27:26 -0400666 for (int i = 0; i < constructorType.columns(); ++i) {
John Stiles9d944232020-08-19 09:56:49 -0400667 if (isFloat) {
668 if (constructor.getFVecComponent(i) != value) {
669 return false;
670 }
671 } else {
672 if (constructor.getIVecComponent(i) != value) {
673 return false;
674 }
675 }
Ethan Nicholasd188c182019-06-10 15:55:38 -0400676 }
John Stiles9d944232020-08-19 09:56:49 -0400677 return true;
678
Ethan Nicholase6592142020-09-08 10:22:09 -0400679 case Type::TypeKind::kScalar:
John Stiles9d944232020-08-19 09:56:49 -0400680 SkASSERT(constructor.fArguments.size() == 1);
681 return is_constant<T>(*constructor.fArguments[0], value);
682
683 default:
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400684 return false;
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400685 }
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400686 }
687 return false;
688 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400689 default:
690 return false;
691 }
692}
693
694/**
695 * Collapses the binary expression pointed to by iter down to just the right side (in both the IR
696 * and CFG structures).
697 */
John Stilesafbf8992020-08-18 10:08:21 -0400698static void delete_left(BasicBlock* b,
699 std::vector<BasicBlock::Node>::iterator* iter,
700 bool* outUpdated,
701 bool* outNeedsRescan) {
Ethan Nicholascb670962017-04-20 19:31:52 -0400702 *outUpdated = true;
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400703 std::unique_ptr<Expression>* target = (*iter)->expression();
John Stilesa5a97b42020-08-18 11:19:07 -0400704 BinaryExpression& bin = (*target)->as<BinaryExpression>();
Ethan Nicholasbf66ffb2020-09-16 22:05:10 +0000705 SkASSERT(!bin.fLeft->hasSideEffects());
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400706 bool result;
Ethan Nicholasbf66ffb2020-09-16 22:05:10 +0000707 if (bin.fOperator == Token::Kind::TK_EQ) {
708 result = b->tryRemoveLValueBefore(iter, bin.fLeft.get());
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400709 } else {
Ethan Nicholasbf66ffb2020-09-16 22:05:10 +0000710 result = b->tryRemoveExpressionBefore(iter, bin.fLeft.get());
Ethan Nicholascb670962017-04-20 19:31:52 -0400711 }
Ethan Nicholasbf66ffb2020-09-16 22:05:10 +0000712 *target = std::move(bin.fRight);
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400713 if (!result) {
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400714 *outNeedsRescan = true;
715 return;
716 }
717 if (*iter == b->fNodes.begin()) {
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400718 *outNeedsRescan = true;
719 return;
720 }
721 --(*iter);
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400722 if ((*iter)->fKind != BasicBlock::Node::kExpression_Kind ||
Ethan Nicholasbf66ffb2020-09-16 22:05:10 +0000723 (*iter)->expression() != &bin.fRight) {
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400724 *outNeedsRescan = true;
725 return;
726 }
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400727 *iter = b->fNodes.erase(*iter);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400728 SkASSERT((*iter)->expression() == target);
Ethan Nicholascb670962017-04-20 19:31:52 -0400729}
730
731/**
732 * Collapses the binary expression pointed to by iter down to just the left side (in both the IR and
733 * CFG structures).
734 */
John Stilesafbf8992020-08-18 10:08:21 -0400735static void delete_right(BasicBlock* b,
736 std::vector<BasicBlock::Node>::iterator* iter,
737 bool* outUpdated,
738 bool* outNeedsRescan) {
Ethan Nicholascb670962017-04-20 19:31:52 -0400739 *outUpdated = true;
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400740 std::unique_ptr<Expression>* target = (*iter)->expression();
John Stilesa5a97b42020-08-18 11:19:07 -0400741 BinaryExpression& bin = (*target)->as<BinaryExpression>();
Ethan Nicholasbf66ffb2020-09-16 22:05:10 +0000742 SkASSERT(!bin.fRight->hasSideEffects());
743 if (!b->tryRemoveExpressionBefore(iter, bin.fRight.get())) {
744 *target = std::move(bin.fLeft);
Ethan Nicholascb670962017-04-20 19:31:52 -0400745 *outNeedsRescan = true;
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400746 return;
Ethan Nicholascb670962017-04-20 19:31:52 -0400747 }
Ethan Nicholasbf66ffb2020-09-16 22:05:10 +0000748 *target = std::move(bin.fLeft);
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400749 if (*iter == b->fNodes.begin()) {
750 *outNeedsRescan = true;
751 return;
752 }
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400753 --(*iter);
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400754 if (((*iter)->fKind != BasicBlock::Node::kExpression_Kind ||
Ethan Nicholasbf66ffb2020-09-16 22:05:10 +0000755 (*iter)->expression() != &bin.fLeft)) {
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400756 *outNeedsRescan = true;
757 return;
758 }
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400759 *iter = b->fNodes.erase(*iter);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400760 SkASSERT((*iter)->expression() == target);
Ethan Nicholascb670962017-04-20 19:31:52 -0400761}
762
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400763/**
764 * Constructs the specified type using a single argument.
765 */
Ethan Nicholas30d30222020-09-11 12:27:26 -0400766static std::unique_ptr<Expression> construct(const Type* type, std::unique_ptr<Expression> v) {
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400767 std::vector<std::unique_ptr<Expression>> args;
768 args.push_back(std::move(v));
Ethan Nicholase6592142020-09-08 10:22:09 -0400769 std::unique_ptr<Expression> result = std::make_unique<Constructor>(-1, type, std::move(args));
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400770 return result;
771}
772
773/**
774 * Used in the implementations of vectorize_left and vectorize_right. Given a vector type and an
775 * expression x, deletes the expression pointed to by iter and replaces it with <type>(x).
776 */
777static void vectorize(BasicBlock* b,
778 std::vector<BasicBlock::Node>::iterator* iter,
779 const Type& type,
780 std::unique_ptr<Expression>* otherExpression,
781 bool* outUpdated,
782 bool* outNeedsRescan) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400783 SkASSERT((*(*iter)->expression())->kind() == Expression::Kind::kBinary);
784 SkASSERT(type.typeKind() == Type::TypeKind::kVector);
Ethan Nicholas30d30222020-09-11 12:27:26 -0400785 SkASSERT((*otherExpression)->type().typeKind() == Type::TypeKind::kScalar);
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400786 *outUpdated = true;
787 std::unique_ptr<Expression>* target = (*iter)->expression();
788 if (!b->tryRemoveExpression(iter)) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400789 *target = construct(&type, std::move(*otherExpression));
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400790 *outNeedsRescan = true;
791 } else {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400792 *target = construct(&type, std::move(*otherExpression));
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400793 if (!b->tryInsertExpression(iter, target)) {
794 *outNeedsRescan = true;
795 }
796 }
797}
798
799/**
800 * Given a binary expression of the form x <op> vec<n>(y), deletes the right side and vectorizes the
801 * left to yield vec<n>(x).
802 */
803static void vectorize_left(BasicBlock* b,
804 std::vector<BasicBlock::Node>::iterator* iter,
805 bool* outUpdated,
806 bool* outNeedsRescan) {
John Stilesa5a97b42020-08-18 11:19:07 -0400807 BinaryExpression& bin = (*(*iter)->expression())->as<BinaryExpression>();
Ethan Nicholasbf66ffb2020-09-16 22:05:10 +0000808 vectorize(b, iter, bin.fRight->type(), &bin.fLeft, outUpdated, outNeedsRescan);
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400809}
810
811/**
812 * Given a binary expression of the form vec<n>(x) <op> y, deletes the left side and vectorizes the
813 * right to yield vec<n>(y).
814 */
815static void vectorize_right(BasicBlock* b,
816 std::vector<BasicBlock::Node>::iterator* iter,
817 bool* outUpdated,
818 bool* outNeedsRescan) {
John Stilesa5a97b42020-08-18 11:19:07 -0400819 BinaryExpression& bin = (*(*iter)->expression())->as<BinaryExpression>();
Ethan Nicholasbf66ffb2020-09-16 22:05:10 +0000820 vectorize(b, iter, bin.fLeft->type(), &bin.fRight, outUpdated, outNeedsRescan);
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400821}
822
823// Mark that an expression which we were writing to is no longer being written to
John Stilesa5a97b42020-08-18 11:19:07 -0400824static void clear_write(Expression& expr) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400825 switch (expr.kind()) {
826 case Expression::Kind::kVariableReference: {
John Stilesa5a97b42020-08-18 11:19:07 -0400827 expr.as<VariableReference>().setRefKind(VariableReference::kRead_RefKind);
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400828 break;
829 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400830 case Expression::Kind::kFieldAccess:
John Stilesa5a97b42020-08-18 11:19:07 -0400831 clear_write(*expr.as<FieldAccess>().fBase);
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400832 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400833 case Expression::Kind::kSwizzle:
John Stilesa5a97b42020-08-18 11:19:07 -0400834 clear_write(*expr.as<Swizzle>().fBase);
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400835 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400836 case Expression::Kind::kIndex:
John Stilesa5a97b42020-08-18 11:19:07 -0400837 clear_write(*expr.as<IndexExpression>().fBase);
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400838 break;
839 default:
840 ABORT("shouldn't be writing to this kind of expression\n");
841 break;
842 }
843}
844
Ethan Nicholascb670962017-04-20 19:31:52 -0400845void Compiler::simplifyExpression(DefinitionMap& definitions,
846 BasicBlock& b,
847 std::vector<BasicBlock::Node>::iterator* iter,
848 std::unordered_set<const Variable*>* undefinedVariables,
849 bool* outUpdated,
850 bool* outNeedsRescan) {
851 Expression* expr = (*iter)->expression()->get();
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400852 SkASSERT(expr);
Ethan Nicholascb670962017-04-20 19:31:52 -0400853 if ((*iter)->fConstantPropagation) {
854 std::unique_ptr<Expression> optimized = expr->constantPropagate(*fIRGenerator, definitions);
855 if (optimized) {
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400856 *outUpdated = true;
Ethan Nicholas30d30222020-09-11 12:27:26 -0400857 optimized = fIRGenerator->coerce(std::move(optimized), expr->type());
Ethan Nicholas1d881522020-09-11 09:32:54 -0400858 SkASSERT(optimized);
Ethan Nicholascb670962017-04-20 19:31:52 -0400859 if (!try_replace_expression(&b, iter, &optimized)) {
860 *outNeedsRescan = true;
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400861 return;
Ethan Nicholascb670962017-04-20 19:31:52 -0400862 }
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400863 SkASSERT((*iter)->fKind == BasicBlock::Node::kExpression_Kind);
Ethan Nicholascb670962017-04-20 19:31:52 -0400864 expr = (*iter)->expression()->get();
Ethan Nicholascb670962017-04-20 19:31:52 -0400865 }
866 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400867 switch (expr->kind()) {
868 case Expression::Kind::kVariableReference: {
John Stilesa5a97b42020-08-18 11:19:07 -0400869 const VariableReference& ref = expr->as<VariableReference>();
Ethan Nicholas8f7e28f2018-03-26 14:24:27 -0400870 const Variable& var = ref.fVariable;
871 if (ref.refKind() != VariableReference::kWrite_RefKind &&
872 ref.refKind() != VariableReference::kPointer_RefKind &&
873 var.fStorage == Variable::kLocal_Storage && !definitions[&var] &&
Ethan Nicholascb670962017-04-20 19:31:52 -0400874 (*undefinedVariables).find(&var) == (*undefinedVariables).end()) {
875 (*undefinedVariables).insert(&var);
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000876 this->error(expr->fOffset,
877 "'" + var.fName + "' has not been assigned");
Ethan Nicholascb670962017-04-20 19:31:52 -0400878 }
879 break;
880 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400881 case Expression::Kind::kTernary: {
John Stiles403a3632020-08-20 12:11:48 -0400882 TernaryExpression* t = &expr->as<TernaryExpression>();
Ethan Nicholase6592142020-09-08 10:22:09 -0400883 if (t->fTest->kind() == Expression::Kind::kBoolLiteral) {
Ethan Nicholascb670962017-04-20 19:31:52 -0400884 // ternary has a constant test, replace it with either the true or
885 // false branch
John Stiles403a3632020-08-20 12:11:48 -0400886 if (t->fTest->as<BoolLiteral>().fValue) {
Ethan Nicholascb670962017-04-20 19:31:52 -0400887 (*iter)->setExpression(std::move(t->fIfTrue));
888 } else {
889 (*iter)->setExpression(std::move(t->fIfFalse));
890 }
891 *outUpdated = true;
892 *outNeedsRescan = true;
893 }
894 break;
895 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400896 case Expression::Kind::kBinary: {
John Stiles403a3632020-08-20 12:11:48 -0400897 BinaryExpression* bin = &expr->as<BinaryExpression>();
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400898 if (dead_assignment(*bin)) {
899 delete_left(&b, iter, outUpdated, outNeedsRescan);
900 break;
901 }
Ethan Nicholasbf66ffb2020-09-16 22:05:10 +0000902 const Type& leftType = bin->fLeft->type();
903 const Type& rightType = bin->fRight->type();
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400904 // collapse useless expressions like x * 1 or x + 0
Ethan Nicholas30d30222020-09-11 12:27:26 -0400905 if (((leftType.typeKind() != Type::TypeKind::kScalar) &&
906 (leftType.typeKind() != Type::TypeKind::kVector)) ||
907 ((rightType.typeKind() != Type::TypeKind::kScalar) &&
908 (rightType.typeKind() != Type::TypeKind::kVector))) {
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400909 break;
910 }
Ethan Nicholasbf66ffb2020-09-16 22:05:10 +0000911 switch (bin->fOperator) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400912 case Token::Kind::TK_STAR:
Ethan Nicholasbf66ffb2020-09-16 22:05:10 +0000913 if (is_constant(*bin->fLeft, 1)) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400914 if (leftType.typeKind() == Type::TypeKind::kVector &&
915 rightType.typeKind() == Type::TypeKind::kScalar) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400916 // float4(1) * x -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400917 vectorize_right(&b, iter, outUpdated, outNeedsRescan);
918 } else {
919 // 1 * x -> x
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400920 // 1 * float4(x) -> float4(x)
921 // float4(1) * float4(x) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400922 delete_left(&b, iter, outUpdated, outNeedsRescan);
923 }
924 }
Ethan Nicholasbf66ffb2020-09-16 22:05:10 +0000925 else if (is_constant(*bin->fLeft, 0)) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400926 if (leftType.typeKind() == Type::TypeKind::kScalar &&
927 rightType.typeKind() == Type::TypeKind::kVector &&
Ethan Nicholasbf66ffb2020-09-16 22:05:10 +0000928 !bin->fRight->hasSideEffects()) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400929 // 0 * float4(x) -> float4(0)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400930 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
931 } else {
932 // 0 * x -> 0
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400933 // float4(0) * x -> float4(0)
934 // float4(0) * float4(x) -> float4(0)
Ethan Nicholasbf66ffb2020-09-16 22:05:10 +0000935 if (!bin->fRight->hasSideEffects()) {
Ethan Nicholas51493ee2017-12-11 12:34:33 -0500936 delete_right(&b, iter, outUpdated, outNeedsRescan);
937 }
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400938 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400939 }
Ethan Nicholasbf66ffb2020-09-16 22:05:10 +0000940 else if (is_constant(*bin->fRight, 1)) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400941 if (leftType.typeKind() == Type::TypeKind::kScalar &&
942 rightType.typeKind() == Type::TypeKind::kVector) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400943 // x * float4(1) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400944 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
945 } else {
946 // x * 1 -> x
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400947 // float4(x) * 1 -> float4(x)
948 // float4(x) * float4(1) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400949 delete_right(&b, iter, outUpdated, outNeedsRescan);
950 }
951 }
Ethan Nicholasbf66ffb2020-09-16 22:05:10 +0000952 else if (is_constant(*bin->fRight, 0)) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400953 if (leftType.typeKind() == Type::TypeKind::kVector &&
954 rightType.typeKind() == Type::TypeKind::kScalar &&
Ethan Nicholasbf66ffb2020-09-16 22:05:10 +0000955 !bin->fLeft->hasSideEffects()) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400956 // float4(x) * 0 -> float4(0)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400957 vectorize_right(&b, iter, outUpdated, outNeedsRescan);
958 } else {
959 // x * 0 -> 0
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400960 // x * float4(0) -> float4(0)
961 // float4(x) * float4(0) -> float4(0)
Ethan Nicholasbf66ffb2020-09-16 22:05:10 +0000962 if (!bin->fLeft->hasSideEffects()) {
Ethan Nicholas51493ee2017-12-11 12:34:33 -0500963 delete_left(&b, iter, outUpdated, outNeedsRescan);
964 }
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400965 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400966 }
967 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400968 case Token::Kind::TK_PLUS:
Ethan Nicholasbf66ffb2020-09-16 22:05:10 +0000969 if (is_constant(*bin->fLeft, 0)) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400970 if (leftType.typeKind() == Type::TypeKind::kVector &&
971 rightType.typeKind() == Type::TypeKind::kScalar) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400972 // float4(0) + x -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400973 vectorize_right(&b, iter, outUpdated, outNeedsRescan);
974 } else {
975 // 0 + x -> x
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400976 // 0 + float4(x) -> float4(x)
977 // float4(0) + float4(x) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400978 delete_left(&b, iter, outUpdated, outNeedsRescan);
979 }
Ethan Nicholasbf66ffb2020-09-16 22:05:10 +0000980 } else if (is_constant(*bin->fRight, 0)) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400981 if (leftType.typeKind() == Type::TypeKind::kScalar &&
982 rightType.typeKind() == Type::TypeKind::kVector) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400983 // x + float4(0) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400984 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
985 } else {
986 // x + 0 -> x
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400987 // float4(x) + 0 -> float4(x)
988 // float4(x) + float4(0) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400989 delete_right(&b, iter, outUpdated, outNeedsRescan);
990 }
Ethan Nicholas56e42712017-04-21 10:23:37 -0400991 }
992 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400993 case Token::Kind::TK_MINUS:
Ethan Nicholasbf66ffb2020-09-16 22:05:10 +0000994 if (is_constant(*bin->fRight, 0)) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400995 if (leftType.typeKind() == Type::TypeKind::kScalar &&
996 rightType.typeKind() == Type::TypeKind::kVector) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400997 // x - float4(0) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400998 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
999 } else {
1000 // x - 0 -> x
Ethan Nicholas5af9ea32017-07-28 15:19:46 -04001001 // float4(x) - 0 -> float4(x)
1002 // float4(x) - float4(0) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -04001003 delete_right(&b, iter, outUpdated, outNeedsRescan);
1004 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001005 }
1006 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001007 case Token::Kind::TK_SLASH:
Ethan Nicholasbf66ffb2020-09-16 22:05:10 +00001008 if (is_constant(*bin->fRight, 1)) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04001009 if (leftType.typeKind() == Type::TypeKind::kScalar &&
1010 rightType.typeKind() == Type::TypeKind::kVector) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -04001011 // x / float4(1) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -04001012 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
1013 } else {
1014 // x / 1 -> x
Ethan Nicholas5af9ea32017-07-28 15:19:46 -04001015 // float4(x) / 1 -> float4(x)
1016 // float4(x) / float4(1) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -04001017 delete_right(&b, iter, outUpdated, outNeedsRescan);
1018 }
Ethan Nicholasbf66ffb2020-09-16 22:05:10 +00001019 } else if (is_constant(*bin->fLeft, 0)) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04001020 if (leftType.typeKind() == Type::TypeKind::kScalar &&
1021 rightType.typeKind() == Type::TypeKind::kVector &&
Ethan Nicholasbf66ffb2020-09-16 22:05:10 +00001022 !bin->fRight->hasSideEffects()) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -04001023 // 0 / float4(x) -> float4(0)
Ethan Nicholasfe53e582017-04-27 16:24:51 -04001024 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
1025 } else {
1026 // 0 / x -> 0
Ethan Nicholas5af9ea32017-07-28 15:19:46 -04001027 // float4(0) / x -> float4(0)
1028 // float4(0) / float4(x) -> float4(0)
Ethan Nicholasbf66ffb2020-09-16 22:05:10 +00001029 if (!bin->fRight->hasSideEffects()) {
Ethan Nicholas51493ee2017-12-11 12:34:33 -05001030 delete_right(&b, iter, outUpdated, outNeedsRescan);
1031 }
Ethan Nicholasfe53e582017-04-27 16:24:51 -04001032 }
1033 }
1034 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001035 case Token::Kind::TK_PLUSEQ:
Ethan Nicholasbf66ffb2020-09-16 22:05:10 +00001036 if (is_constant(*bin->fRight, 0)) {
1037 clear_write(*bin->fLeft);
Ethan Nicholasfe53e582017-04-27 16:24:51 -04001038 delete_right(&b, iter, outUpdated, outNeedsRescan);
1039 }
1040 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001041 case Token::Kind::TK_MINUSEQ:
Ethan Nicholasbf66ffb2020-09-16 22:05:10 +00001042 if (is_constant(*bin->fRight, 0)) {
1043 clear_write(*bin->fLeft);
Ethan Nicholasfe53e582017-04-27 16:24:51 -04001044 delete_right(&b, iter, outUpdated, outNeedsRescan);
1045 }
1046 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001047 case Token::Kind::TK_STAREQ:
Ethan Nicholasbf66ffb2020-09-16 22:05:10 +00001048 if (is_constant(*bin->fRight, 1)) {
1049 clear_write(*bin->fLeft);
Ethan Nicholasfe53e582017-04-27 16:24:51 -04001050 delete_right(&b, iter, outUpdated, outNeedsRescan);
1051 }
1052 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001053 case Token::Kind::TK_SLASHEQ:
Ethan Nicholasbf66ffb2020-09-16 22:05:10 +00001054 if (is_constant(*bin->fRight, 1)) {
1055 clear_write(*bin->fLeft);
Ethan Nicholascb670962017-04-20 19:31:52 -04001056 delete_right(&b, iter, outUpdated, outNeedsRescan);
1057 }
1058 break;
1059 default:
1060 break;
1061 }
Ethan Nicholas409f6f02019-09-17 12:34:39 -04001062 break;
1063 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001064 case Expression::Kind::kSwizzle: {
John Stiles403a3632020-08-20 12:11:48 -04001065 Swizzle& s = expr->as<Swizzle>();
Ethan Nicholas409f6f02019-09-17 12:34:39 -04001066 // detect identity swizzles like foo.rgba
Ethan Nicholas30d30222020-09-11 12:27:26 -04001067 if ((int) s.fComponents.size() == s.fBase->type().columns()) {
Ethan Nicholas409f6f02019-09-17 12:34:39 -04001068 bool identity = true;
1069 for (int i = 0; i < (int) s.fComponents.size(); ++i) {
1070 if (s.fComponents[i] != i) {
1071 identity = false;
1072 break;
1073 }
1074 }
1075 if (identity) {
1076 *outUpdated = true;
1077 if (!try_replace_expression(&b, iter, &s.fBase)) {
1078 *outNeedsRescan = true;
1079 return;
1080 }
1081 SkASSERT((*iter)->fKind == BasicBlock::Node::kExpression_Kind);
1082 break;
1083 }
1084 }
1085 // detect swizzles of swizzles, e.g. replace foo.argb.r000 with foo.a000
Ethan Nicholase6592142020-09-08 10:22:09 -04001086 if (s.fBase->kind() == Expression::Kind::kSwizzle) {
John Stilesa5a97b42020-08-18 11:19:07 -04001087 Swizzle& base = s.fBase->as<Swizzle>();
Ethan Nicholas409f6f02019-09-17 12:34:39 -04001088 std::vector<int> final;
1089 for (int c : s.fComponents) {
Brian Osman25647672020-09-15 15:16:56 -04001090 final.push_back(base.fComponents[c]);
Ethan Nicholas409f6f02019-09-17 12:34:39 -04001091 }
1092 *outUpdated = true;
1093 std::unique_ptr<Expression> replacement(new Swizzle(*fContext, base.fBase->clone(),
1094 std::move(final)));
1095 if (!try_replace_expression(&b, iter, &replacement)) {
1096 *outNeedsRescan = true;
1097 return;
1098 }
1099 SkASSERT((*iter)->fKind == BasicBlock::Node::kExpression_Kind);
Ethan Nicholas409f6f02019-09-17 12:34:39 -04001100 }
John Stiles30212b72020-06-11 17:55:07 -04001101 break;
Ethan Nicholascb670962017-04-20 19:31:52 -04001102 }
1103 default:
1104 break;
1105 }
1106}
1107
John Stiles92219b42020-06-15 12:32:24 -04001108// Returns true if this statement could potentially execute a break at the current level. We ignore
1109// nested loops and switches, since any breaks inside of them will merely break the loop / switch.
John Stilesb92641c2020-08-31 18:09:01 -04001110static bool contains_conditional_break(Statement& stmt) {
1111 class ContainsConditionalBreak : public ProgramVisitor {
1112 public:
1113 bool visitStatement(const Statement& stmt) override {
Ethan Nicholase6592142020-09-08 10:22:09 -04001114 switch (stmt.kind()) {
1115 case Statement::Kind::kBlock:
John Stilesb92641c2020-08-31 18:09:01 -04001116 return this->INHERITED::visitStatement(stmt);
1117
Ethan Nicholase6592142020-09-08 10:22:09 -04001118 case Statement::Kind::kBreak:
John Stilesb92641c2020-08-31 18:09:01 -04001119 return fInConditional > 0;
1120
Ethan Nicholase6592142020-09-08 10:22:09 -04001121 case Statement::Kind::kIf: {
John Stilesb92641c2020-08-31 18:09:01 -04001122 ++fInConditional;
1123 bool result = this->INHERITED::visitStatement(stmt);
1124 --fInConditional;
1125 return result;
1126 }
1127
1128 default:
1129 return false;
1130 }
1131 }
1132
1133 int fInConditional = 0;
1134 using INHERITED = ProgramVisitor;
1135 };
1136
1137 return ContainsConditionalBreak{}.visitStatement(stmt);
John Stiles92219b42020-06-15 12:32:24 -04001138}
1139
Ethan Nicholas5005a222018-08-24 13:06:27 -04001140// returns true if this statement definitely executes a break at the current level (we ignore
1141// nested loops and switches, since any breaks inside of them will merely break the loop / switch)
John Stilesb92641c2020-08-31 18:09:01 -04001142static bool contains_unconditional_break(Statement& stmt) {
1143 class ContainsUnconditionalBreak : public ProgramVisitor {
1144 public:
1145 bool visitStatement(const Statement& stmt) override {
Ethan Nicholase6592142020-09-08 10:22:09 -04001146 switch (stmt.kind()) {
1147 case Statement::Kind::kBlock:
John Stilesb92641c2020-08-31 18:09:01 -04001148 return this->INHERITED::visitStatement(stmt);
1149
Ethan Nicholase6592142020-09-08 10:22:09 -04001150 case Statement::Kind::kBreak:
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001151 return true;
John Stilesb92641c2020-08-31 18:09:01 -04001152
1153 default:
1154 return false;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001155 }
John Stilesb92641c2020-08-31 18:09:01 -04001156 }
John Stiles92219b42020-06-15 12:32:24 -04001157
John Stilesb92641c2020-08-31 18:09:01 -04001158 using INHERITED = ProgramVisitor;
1159 };
John Stiles92219b42020-06-15 12:32:24 -04001160
John Stilesb92641c2020-08-31 18:09:01 -04001161 return ContainsUnconditionalBreak{}.visitStatement(stmt);
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001162}
1163
John Stiles92219b42020-06-15 12:32:24 -04001164static void move_all_but_break(std::unique_ptr<Statement>& stmt,
1165 std::vector<std::unique_ptr<Statement>>* target) {
Ethan Nicholase6592142020-09-08 10:22:09 -04001166 switch (stmt->kind()) {
1167 case Statement::Kind::kBlock: {
John Stiles92219b42020-06-15 12:32:24 -04001168 // Recurse into the block.
1169 Block& block = static_cast<Block&>(*stmt);
1170
1171 std::vector<std::unique_ptr<Statement>> blockStmts;
1172 blockStmts.reserve(block.fStatements.size());
1173 for (std::unique_ptr<Statement>& statementInBlock : block.fStatements) {
1174 move_all_but_break(statementInBlock, &blockStmts);
Ethan Nicholas739e1ca2020-06-11 12:16:14 -04001175 }
John Stiles92219b42020-06-15 12:32:24 -04001176
1177 target->push_back(std::make_unique<Block>(block.fOffset, std::move(blockStmts),
1178 block.fSymbols, block.fIsScope));
Ethan Nicholas739e1ca2020-06-11 12:16:14 -04001179 break;
John Stiles92219b42020-06-15 12:32:24 -04001180 }
1181
Ethan Nicholase6592142020-09-08 10:22:09 -04001182 case Statement::Kind::kBreak:
John Stiles92219b42020-06-15 12:32:24 -04001183 // Do not append a break to the target.
1184 break;
1185
Ethan Nicholas739e1ca2020-06-11 12:16:14 -04001186 default:
John Stiles92219b42020-06-15 12:32:24 -04001187 // Append normal statements to the target.
1188 target->push_back(std::move(stmt));
1189 break;
Ethan Nicholas739e1ca2020-06-11 12:16:14 -04001190 }
1191}
1192
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001193// Returns a block containing all of the statements that will be run if the given case matches
1194// (which, owing to the statements being owned by unique_ptrs, means the switch itself will be
1195// broken by this call and must then be discarded).
1196// Returns null (and leaves the switch unmodified) if no such simple reduction is possible, such as
1197// when break statements appear inside conditionals.
John Stiles92219b42020-06-15 12:32:24 -04001198static std::unique_ptr<Statement> block_for_case(SwitchStatement* switchStatement,
1199 SwitchCase* caseToCapture) {
1200 // We have to be careful to not move any of the pointers until after we're sure we're going to
1201 // succeed, so before we make any changes at all, we check the switch-cases to decide on a plan
1202 // of action. First, find the switch-case we are interested in.
1203 auto iter = switchStatement->fCases.begin();
1204 for (; iter != switchStatement->fCases.end(); ++iter) {
1205 if (iter->get() == caseToCapture) {
1206 break;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001207 }
John Stiles92219b42020-06-15 12:32:24 -04001208 }
1209
1210 // Next, walk forward through the rest of the switch. If we find a conditional break, we're
1211 // stuck and can't simplify at all. If we find an unconditional break, we have a range of
1212 // statements that we can use for simplification.
1213 auto startIter = iter;
1214 Statement* unconditionalBreakStmt = nullptr;
1215 for (; iter != switchStatement->fCases.end(); ++iter) {
1216 for (std::unique_ptr<Statement>& stmt : (*iter)->fStatements) {
1217 if (contains_conditional_break(*stmt)) {
1218 // We can't reduce switch-cases to a block when they have conditional breaks.
1219 return nullptr;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001220 }
John Stiles92219b42020-06-15 12:32:24 -04001221
1222 if (contains_unconditional_break(*stmt)) {
1223 // We found an unconditional break. We can use this block, but we need to strip
1224 // out the break statement.
1225 unconditionalBreakStmt = stmt.get();
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001226 break;
1227 }
1228 }
John Stiles92219b42020-06-15 12:32:24 -04001229
1230 if (unconditionalBreakStmt != nullptr) {
1231 break;
1232 }
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001233 }
John Stiles92219b42020-06-15 12:32:24 -04001234
1235 // We fell off the bottom of the switch or encountered a break. We know the range of statements
1236 // that we need to move over, and we know it's safe to do so.
1237 std::vector<std::unique_ptr<Statement>> caseStmts;
1238
1239 // We can move over most of the statements as-is.
1240 while (startIter != iter) {
1241 for (std::unique_ptr<Statement>& stmt : (*startIter)->fStatements) {
1242 caseStmts.push_back(std::move(stmt));
1243 }
1244 ++startIter;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001245 }
John Stiles92219b42020-06-15 12:32:24 -04001246
1247 // If we found an unconditional break at the end, we need to move what we can while avoiding
1248 // that break.
1249 if (unconditionalBreakStmt != nullptr) {
1250 for (std::unique_ptr<Statement>& stmt : (*startIter)->fStatements) {
1251 if (stmt.get() == unconditionalBreakStmt) {
1252 move_all_but_break(stmt, &caseStmts);
1253 unconditionalBreakStmt = nullptr;
1254 break;
1255 }
1256
1257 caseStmts.push_back(std::move(stmt));
1258 }
1259 }
1260
1261 SkASSERT(unconditionalBreakStmt == nullptr); // Verify that we fixed the unconditional break.
1262
1263 // Return our newly-synthesized block.
1264 return std::make_unique<Block>(/*offset=*/-1, std::move(caseStmts), switchStatement->fSymbols);
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001265}
1266
Ethan Nicholascb670962017-04-20 19:31:52 -04001267void Compiler::simplifyStatement(DefinitionMap& definitions,
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001268 BasicBlock& b,
1269 std::vector<BasicBlock::Node>::iterator* iter,
1270 std::unordered_set<const Variable*>* undefinedVariables,
1271 bool* outUpdated,
1272 bool* outNeedsRescan) {
Ethan Nicholascb670962017-04-20 19:31:52 -04001273 Statement* stmt = (*iter)->statement()->get();
Ethan Nicholase6592142020-09-08 10:22:09 -04001274 switch (stmt->kind()) {
1275 case Statement::Kind::kVarDeclaration: {
John Stilesa5a97b42020-08-18 11:19:07 -04001276 const auto& varDecl = stmt->as<VarDeclaration>();
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001277 if (varDecl.fVar->dead() &&
1278 (!varDecl.fValue ||
1279 !varDecl.fValue->hasSideEffects())) {
1280 if (varDecl.fValue) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001281 SkASSERT((*iter)->statement()->get() == stmt);
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001282 if (!b.tryRemoveExpressionBefore(iter, varDecl.fValue.get())) {
1283 *outNeedsRescan = true;
Ethan Nicholascb670962017-04-20 19:31:52 -04001284 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001285 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001286 (*iter)->setStatement(std::unique_ptr<Statement>(new Nop()));
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001287 *outUpdated = true;
Ethan Nicholascb670962017-04-20 19:31:52 -04001288 }
1289 break;
1290 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001291 case Statement::Kind::kIf: {
John Stilesa5a97b42020-08-18 11:19:07 -04001292 IfStatement& i = stmt->as<IfStatement>();
Ethan Nicholase6592142020-09-08 10:22:09 -04001293 if (i.fTest->kind() == Expression::Kind::kBoolLiteral) {
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001294 // constant if, collapse down to a single branch
John Stilesa5a97b42020-08-18 11:19:07 -04001295 if (i.fTest->as<BoolLiteral>().fValue) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001296 SkASSERT(i.fIfTrue);
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001297 (*iter)->setStatement(std::move(i.fIfTrue));
1298 } else {
1299 if (i.fIfFalse) {
1300 (*iter)->setStatement(std::move(i.fIfFalse));
1301 } else {
1302 (*iter)->setStatement(std::unique_ptr<Statement>(new Nop()));
1303 }
1304 }
1305 *outUpdated = true;
1306 *outNeedsRescan = true;
1307 break;
1308 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001309 if (i.fIfFalse && i.fIfFalse->isEmpty()) {
1310 // else block doesn't do anything, remove it
1311 i.fIfFalse.reset();
1312 *outUpdated = true;
1313 *outNeedsRescan = true;
1314 }
1315 if (!i.fIfFalse && i.fIfTrue->isEmpty()) {
1316 // if block doesn't do anything, no else block
1317 if (i.fTest->hasSideEffects()) {
1318 // test has side effects, keep it
1319 (*iter)->setStatement(std::unique_ptr<Statement>(
1320 new ExpressionStatement(std::move(i.fTest))));
1321 } else {
1322 // no if, no else, no test side effects, kill the whole if
1323 // statement
1324 (*iter)->setStatement(std::unique_ptr<Statement>(new Nop()));
1325 }
1326 *outUpdated = true;
1327 *outNeedsRescan = true;
1328 }
1329 break;
1330 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001331 case Statement::Kind::kSwitch: {
John Stilesa5a97b42020-08-18 11:19:07 -04001332 SwitchStatement& s = stmt->as<SwitchStatement>();
Ethan Nicholas34b19c52020-09-14 11:33:47 -04001333 int64_t switchValue;
1334 if (fIRGenerator->getConstantInt(*s.fValue, &switchValue)) {
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001335 // switch is constant, replace it with the case that matches
1336 bool found = false;
1337 SwitchCase* defaultCase = nullptr;
John Stiles9d944232020-08-19 09:56:49 -04001338 for (const std::unique_ptr<SwitchCase>& c : s.fCases) {
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001339 if (!c->fValue) {
1340 defaultCase = c.get();
1341 continue;
1342 }
Ethan Nicholas34b19c52020-09-14 11:33:47 -04001343 int64_t caseValue;
1344 SkAssertResult(fIRGenerator->getConstantInt(*c->fValue, &caseValue));
1345 if (caseValue == switchValue) {
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001346 std::unique_ptr<Statement> newBlock = block_for_case(&s, c.get());
1347 if (newBlock) {
1348 (*iter)->setStatement(std::move(newBlock));
John Stiles9d944232020-08-19 09:56:49 -04001349 found = true;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001350 break;
1351 } else {
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -04001352 if (s.fIsStatic && !(fFlags & kPermitInvalidStaticTests_Flag)) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001353 this->error(s.fOffset,
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001354 "static switch contains non-static conditional break");
1355 s.fIsStatic = false;
1356 }
1357 return; // can't simplify
1358 }
1359 }
1360 }
1361 if (!found) {
1362 // no matching case. use default if it exists, or kill the whole thing
1363 if (defaultCase) {
1364 std::unique_ptr<Statement> newBlock = block_for_case(&s, defaultCase);
1365 if (newBlock) {
1366 (*iter)->setStatement(std::move(newBlock));
1367 } else {
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -04001368 if (s.fIsStatic && !(fFlags & kPermitInvalidStaticTests_Flag)) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001369 this->error(s.fOffset,
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001370 "static switch contains non-static conditional break");
1371 s.fIsStatic = false;
1372 }
1373 return; // can't simplify
1374 }
1375 } else {
1376 (*iter)->setStatement(std::unique_ptr<Statement>(new Nop()));
1377 }
1378 }
1379 *outUpdated = true;
1380 *outNeedsRescan = true;
1381 }
1382 break;
1383 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001384 case Statement::Kind::kExpression: {
John Stilesa5a97b42020-08-18 11:19:07 -04001385 ExpressionStatement& e = stmt->as<ExpressionStatement>();
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001386 SkASSERT((*iter)->statement()->get() == &e);
Ethan Nicholascb670962017-04-20 19:31:52 -04001387 if (!e.fExpression->hasSideEffects()) {
1388 // Expression statement with no side effects, kill it
1389 if (!b.tryRemoveExpressionBefore(iter, e.fExpression.get())) {
1390 *outNeedsRescan = true;
1391 }
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001392 SkASSERT((*iter)->statement()->get() == stmt);
Ethan Nicholascb670962017-04-20 19:31:52 -04001393 (*iter)->setStatement(std::unique_ptr<Statement>(new Nop()));
1394 *outUpdated = true;
1395 }
1396 break;
1397 }
1398 default:
1399 break;
1400 }
1401}
1402
John Stiles0cc193a2020-09-09 09:39:34 -04001403bool Compiler::scanCFG(FunctionDefinition& f) {
1404 bool madeChanges = false;
1405
Ethan Nicholascb670962017-04-20 19:31:52 -04001406 CFG cfg = CFGGenerator().getCFG(f);
1407 this->computeDataFlow(&cfg);
ethannicholas22f939e2016-10-13 13:25:34 -07001408
1409 // check for unreachable code
1410 for (size_t i = 0; i < cfg.fBlocks.size(); i++) {
John Stiles0cc193a2020-09-09 09:39:34 -04001411 const BasicBlock& block = cfg.fBlocks[i];
1412 if (i != cfg.fStart && !block.fEntrances.size() && block.fNodes.size()) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001413 int offset;
John Stiles0cc193a2020-09-09 09:39:34 -04001414 const BasicBlock::Node& node = block.fNodes[0];
1415 switch (node.fKind) {
Ethan Nicholas86a43402017-01-19 13:32:00 -05001416 case BasicBlock::Node::kStatement_Kind:
John Stiles0cc193a2020-09-09 09:39:34 -04001417 offset = (*node.statement())->fOffset;
Ethan Nicholas86a43402017-01-19 13:32:00 -05001418 break;
1419 case BasicBlock::Node::kExpression_Kind:
John Stiles0cc193a2020-09-09 09:39:34 -04001420 offset = (*node.expression())->fOffset;
1421 if ((*node.expression())->is<BoolLiteral>()) {
Ethan Nicholas70728ef2020-05-28 07:09:00 -04001422 // Function inlining can generate do { ... } while(false) loops which always
1423 // break, so the boolean condition is considered unreachable. Since not
1424 // being able to reach a literal is a non-issue in the first place, we
1425 // don't report an error in this case.
1426 continue;
1427 }
Ethan Nicholas86a43402017-01-19 13:32:00 -05001428 break;
1429 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001430 this->error(offset, String("unreachable"));
ethannicholas22f939e2016-10-13 13:25:34 -07001431 }
1432 }
1433 if (fErrorCount) {
John Stiles0cc193a2020-09-09 09:39:34 -04001434 return madeChanges;
ethannicholas22f939e2016-10-13 13:25:34 -07001435 }
1436
Ethan Nicholascb670962017-04-20 19:31:52 -04001437 // check for dead code & undefined variables, perform constant propagation
1438 std::unordered_set<const Variable*> undefinedVariables;
1439 bool updated;
1440 bool needsRescan = false;
1441 do {
1442 if (needsRescan) {
1443 cfg = CFGGenerator().getCFG(f);
1444 this->computeDataFlow(&cfg);
1445 needsRescan = false;
Ethan Nicholas113628d2017-02-02 16:11:39 -05001446 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001447
1448 updated = false;
Ethan Nicholas1de14812020-06-19 15:32:49 -04001449 bool first = true;
Ethan Nicholascb670962017-04-20 19:31:52 -04001450 for (BasicBlock& b : cfg.fBlocks) {
Ethan Nicholas1de14812020-06-19 15:32:49 -04001451 if (!first && b.fEntrances.empty()) {
1452 // Block was reachable before optimization, but has since become unreachable. In
1453 // addition to being dead code, it's broken - since control flow can't reach it, no
1454 // prior variable definitions can reach it, and therefore variables might look to
1455 // have not been properly assigned. Kill it.
Brian Osmandb16c482020-09-09 15:15:06 -04001456
1457 // We need to do this in two steps. For any variable declarations, the node list
1458 // will contain statement nodes for each VarDeclaration, and then a statement for
1459 // the VarDeclarationsStatement. When we replace the VDS with a Nop, we delete the
1460 // storage of the unique_ptr that the VD nodes are pointing to. So we remove those
1461 // from the node list entirely, first.
1462 b.fNodes.erase(
1463 std::remove_if(b.fNodes.begin(), b.fNodes.end(),
1464 [](const BasicBlock::Node& node) {
1465 return node.fKind == BasicBlock::Node::kStatement_Kind &&
1466 (*node.statement())->is<VarDeclaration>();
1467 }),
1468 b.fNodes.end());
1469
1470 // Now replace any remaining statements in the block with Nops.
Ethan Nicholas1de14812020-06-19 15:32:49 -04001471 for (BasicBlock::Node& node : b.fNodes) {
1472 if (node.fKind == BasicBlock::Node::kStatement_Kind &&
John Stiles0cc193a2020-09-09 09:39:34 -04001473 !(*node.statement())->is<Nop>()) {
1474 node.setStatement(std::make_unique<Nop>());
1475 madeChanges = true;
Ethan Nicholas1de14812020-06-19 15:32:49 -04001476 }
1477 }
1478 continue;
1479 }
1480 first = false;
Ethan Nicholascb670962017-04-20 19:31:52 -04001481 DefinitionMap definitions = b.fBefore;
1482
1483 for (auto iter = b.fNodes.begin(); iter != b.fNodes.end() && !needsRescan; ++iter) {
1484 if (iter->fKind == BasicBlock::Node::kExpression_Kind) {
1485 this->simplifyExpression(definitions, b, &iter, &undefinedVariables, &updated,
1486 &needsRescan);
1487 } else {
1488 this->simplifyStatement(definitions, b, &iter, &undefinedVariables, &updated,
John Stiles0cc193a2020-09-09 09:39:34 -04001489 &needsRescan);
Ethan Nicholascb670962017-04-20 19:31:52 -04001490 }
Ethan Nicholas4b330df2017-05-17 10:52:55 -04001491 if (needsRescan) {
1492 break;
1493 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001494 this->addDefinitions(*iter, &definitions);
1495 }
Brian Osman01a3eb42020-09-14 11:32:49 -04001496
1497 if (needsRescan) {
1498 break;
1499 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001500 }
John Stiles0cc193a2020-09-09 09:39:34 -04001501 madeChanges |= updated;
Ethan Nicholascb670962017-04-20 19:31:52 -04001502 } while (updated);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001503 SkASSERT(!needsRescan);
ethannicholas22f939e2016-10-13 13:25:34 -07001504
Ethan Nicholas91a10532017-06-22 11:24:38 -04001505 // verify static ifs & switches, clean up dead variable decls
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001506 for (BasicBlock& b : cfg.fBlocks) {
1507 DefinitionMap definitions = b.fBefore;
1508
Ethan Nicholas91a10532017-06-22 11:24:38 -04001509 for (auto iter = b.fNodes.begin(); iter != b.fNodes.end() && !needsRescan;) {
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001510 if (iter->fKind == BasicBlock::Node::kStatement_Kind) {
1511 const Statement& s = **iter->statement();
Ethan Nicholase6592142020-09-08 10:22:09 -04001512 switch (s.kind()) {
1513 case Statement::Kind::kIf:
John Stilesa5a97b42020-08-18 11:19:07 -04001514 if (s.as<IfStatement>().fIsStatic &&
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -04001515 !(fFlags & kPermitInvalidStaticTests_Flag)) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001516 this->error(s.fOffset, "static if has non-static test");
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001517 }
Ethan Nicholas91a10532017-06-22 11:24:38 -04001518 ++iter;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001519 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001520 case Statement::Kind::kSwitch:
John Stilesa5a97b42020-08-18 11:19:07 -04001521 if (s.as<SwitchStatement>().fIsStatic &&
John Stiles0cc193a2020-09-09 09:39:34 -04001522 !(fFlags & kPermitInvalidStaticTests_Flag)) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001523 this->error(s.fOffset, "static switch has non-static test");
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001524 }
Ethan Nicholas91a10532017-06-22 11:24:38 -04001525 ++iter;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001526 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001527 case Statement::Kind::kVarDeclarations: {
John Stilesa5a97b42020-08-18 11:19:07 -04001528 VarDeclarations& decls = *s.as<VarDeclarationsStatement>().fDeclaration;
John Stiles0cc193a2020-09-09 09:39:34 -04001529 decls.fVars.erase(
1530 std::remove_if(decls.fVars.begin(), decls.fVars.end(),
1531 [&](const std::unique_ptr<Statement>& var) {
1532 bool nop = var->is<Nop>();
1533 madeChanges |= nop;
1534 return nop;
1535 }),
1536 decls.fVars.end());
1537 if (decls.fVars.empty()) {
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001538 iter = b.fNodes.erase(iter);
1539 } else {
1540 ++iter;
1541 }
1542 break;
1543 }
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001544 default:
Ethan Nicholas91a10532017-06-22 11:24:38 -04001545 ++iter;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001546 break;
1547 }
Ethan Nicholas91a10532017-06-22 11:24:38 -04001548 } else {
1549 ++iter;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001550 }
1551 }
1552 }
1553
ethannicholas22f939e2016-10-13 13:25:34 -07001554 // check for missing return
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001555 if (f.fDeclaration.fReturnType != *fContext->fVoid_Type) {
ethannicholas22f939e2016-10-13 13:25:34 -07001556 if (cfg.fBlocks[cfg.fExit].fEntrances.size()) {
Ethan Nicholasdb80f692019-11-22 14:06:12 -05001557 this->error(f.fOffset, String("function '" + String(f.fDeclaration.fName) +
1558 "' can exit without returning a value"));
ethannicholas22f939e2016-10-13 13:25:34 -07001559 }
1560 }
John Stiles0cc193a2020-09-09 09:39:34 -04001561
1562 return madeChanges;
ethannicholas22f939e2016-10-13 13:25:34 -07001563}
1564
Ethan Nicholas91164d12019-05-15 15:29:54 -04001565void Compiler::registerExternalValue(ExternalValue* value) {
1566 fIRGenerator->fRootSymbolTable->addWithoutOwnership(value->fName, value);
1567}
1568
Ethan Nicholasc18bb512020-07-28 14:46:53 -04001569const Symbol* Compiler::takeOwnership(std::unique_ptr<const Symbol> symbol) {
John Stiles3ae071e2020-08-05 15:29:29 -04001570 return fIRGenerator->fRootSymbolTable->takeOwnershipOfSymbol(std::move(symbol));
Ethan Nicholas91164d12019-05-15 15:29:54 -04001571}
1572
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001573std::unique_ptr<Program> Compiler::convertProgram(Program::Kind kind, String text,
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001574 const Program::Settings& settings) {
ethannicholasb3058bd2016-07-01 08:22:01 -07001575 fErrorText = "";
1576 fErrorCount = 0;
John Stiles7b463002020-08-31 17:29:21 -04001577 fInliner.reset(context(), settings);
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001578 std::vector<std::unique_ptr<ProgramElement>>* inherited;
ethannicholasd598f792016-07-25 10:08:54 -07001579 std::vector<std::unique_ptr<ProgramElement>> elements;
ethannicholasb3058bd2016-07-01 08:22:01 -07001580 switch (kind) {
1581 case Program::kVertex_Kind:
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001582 inherited = &fVertexInclude;
1583 fIRGenerator->fSymbolTable = fVertexSymbolTable;
John Stiles810c8cf2020-08-26 19:46:27 -04001584 fIRGenerator->fIntrinsics = fGPUIntrinsics.get();
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001585 fIRGenerator->start(&settings, inherited);
ethannicholasb3058bd2016-07-01 08:22:01 -07001586 break;
1587 case Program::kFragment_Kind:
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001588 inherited = &fFragmentInclude;
1589 fIRGenerator->fSymbolTable = fFragmentSymbolTable;
John Stiles810c8cf2020-08-26 19:46:27 -04001590 fIRGenerator->fIntrinsics = fGPUIntrinsics.get();
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001591 fIRGenerator->start(&settings, inherited);
ethannicholasb3058bd2016-07-01 08:22:01 -07001592 break;
Ethan Nicholas52cad152017-02-16 16:37:32 -05001593 case Program::kGeometry_Kind:
Ethan Nicholasc18bb512020-07-28 14:46:53 -04001594 this->loadGeometryIntrinsics();
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001595 inherited = &fGeometryInclude;
1596 fIRGenerator->fSymbolTable = fGeometrySymbolTable;
John Stiles810c8cf2020-08-26 19:46:27 -04001597 fIRGenerator->fIntrinsics = fGPUIntrinsics.get();
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001598 fIRGenerator->start(&settings, inherited);
Ethan Nicholas52cad152017-02-16 16:37:32 -05001599 break;
Ethan Nicholasb33fa3f2020-08-06 13:00:19 -04001600 case Program::kFragmentProcessor_Kind: {
Brian Osmandd496172020-08-08 08:17:18 -04001601#if !SKSL_STANDALONE
Ethan Nicholasc18bb512020-07-28 14:46:53 -04001602 {
1603 Rehydrator rehydrator(fContext.get(), fGpuSymbolTable, this,
1604 SKSL_INCLUDE_sksl_fp,
1605 SKSL_INCLUDE_sksl_fp_LENGTH);
1606 fFPSymbolTable = rehydrator.symbolTable();
1607 fFPInclude = rehydrator.elements();
1608 }
1609 inherited = &fFPInclude;
1610 fIRGenerator->fSymbolTable = fFPSymbolTable;
John Stiles810c8cf2020-08-26 19:46:27 -04001611 fIRGenerator->fIntrinsics = fGPUIntrinsics.get();
Ethan Nicholasc18bb512020-07-28 14:46:53 -04001612 fIRGenerator->start(&settings, inherited);
1613 break;
1614#else
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001615 inherited = nullptr;
Ethan Nicholas8da1e652019-05-24 11:01:59 -04001616 fIRGenerator->fSymbolTable = fGpuSymbolTable;
Ethan Nicholasb33fa3f2020-08-06 13:00:19 -04001617 fIRGenerator->start(&settings, /*inherited=*/nullptr, /*builtin=*/true);
John Stiles810c8cf2020-08-26 19:46:27 -04001618 fIRGenerator->fIntrinsics = fGPUIntrinsics.get();
Ethan Nicholasb33fa3f2020-08-06 13:00:19 -04001619 std::ifstream in(SKSL_FP_INCLUDE);
1620 std::string stdText{std::istreambuf_iterator<char>(in),
1621 std::istreambuf_iterator<char>()};
1622 if (in.rdstate()) {
1623 printf("error reading %s\n", SKSL_FP_INCLUDE);
1624 abort();
1625 }
1626 const String* source = fGpuSymbolTable->takeOwnershipOfString(
1627 std::make_unique<String>(stdText.c_str()));
1628 fIRGenerator->convertProgram(kind, source->c_str(), source->length(), &elements);
Ethan Nicholasc18bb512020-07-28 14:46:53 -04001629 fIRGenerator->fIsBuiltinCode = false;
Ethan Nicholas762466e2017-06-29 10:03:38 -04001630 break;
Ethan Nicholasc18bb512020-07-28 14:46:53 -04001631#endif
Ethan Nicholasb33fa3f2020-08-06 13:00:19 -04001632 }
Ethan Nicholas8da1e652019-05-24 11:01:59 -04001633 case Program::kPipelineStage_Kind:
Ethan Nicholasc18bb512020-07-28 14:46:53 -04001634 this->loadPipelineIntrinsics();
Ethan Nicholas8da1e652019-05-24 11:01:59 -04001635 inherited = &fPipelineInclude;
1636 fIRGenerator->fSymbolTable = fPipelineSymbolTable;
John Stiles810c8cf2020-08-26 19:46:27 -04001637 fIRGenerator->fIntrinsics = fGPUIntrinsics.get();
Ethan Nicholas8da1e652019-05-24 11:01:59 -04001638 fIRGenerator->start(&settings, inherited);
1639 break;
Ethan Nicholas746035a2019-04-23 13:31:09 -04001640 case Program::kGeneric_Kind:
Ethan Nicholasc18bb512020-07-28 14:46:53 -04001641 this->loadInterpreterIntrinsics();
Brian Osmaneac49832020-09-18 11:49:22 -04001642 inherited = nullptr;
Ethan Nicholas8da1e652019-05-24 11:01:59 -04001643 fIRGenerator->fSymbolTable = fInterpreterSymbolTable;
John Stiles810c8cf2020-08-26 19:46:27 -04001644 fIRGenerator->fIntrinsics = fInterpreterIntrinsics.get();
Brian Osmaneac49832020-09-18 11:49:22 -04001645 fIRGenerator->start(&settings, /*inherited=*/nullptr);
Ethan Nicholas0d997662019-04-08 09:46:01 -04001646 break;
ethannicholasb3058bd2016-07-01 08:22:01 -07001647 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001648 std::unique_ptr<String> textPtr(new String(std::move(text)));
1649 fSource = textPtr.get();
Ethan Nicholasc18bb512020-07-28 14:46:53 -04001650 fIRGenerator->convertProgram(kind, textPtr->c_str(), textPtr->size(), &elements);
John Stilesfbd050b2020-08-03 13:21:46 -04001651 auto result = std::make_unique<Program>(kind,
1652 std::move(textPtr),
1653 settings,
1654 fContext,
1655 inherited,
1656 std::move(elements),
1657 fIRGenerator->fSymbolTable,
1658 fIRGenerator->fInputs);
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001659 if (fErrorCount) {
1660 return nullptr;
1661 }
Ethan Nicholas34b19c52020-09-14 11:33:47 -04001662 if (settings.fOptimize && !this->optimize(*result)) {
1663 return nullptr;
1664 }
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001665 return result;
1666}
1667
Ethan Nicholas00543112018-07-31 09:44:36 -04001668bool Compiler::optimize(Program& program) {
1669 SkASSERT(!fErrorCount);
Ethan Nicholas34b19c52020-09-14 11:33:47 -04001670 fIRGenerator->fKind = program.fKind;
1671 fIRGenerator->fSettings = &program.fSettings;
John Stiles7954d6c2020-09-01 10:53:02 -04001672
Ethan Nicholas34b19c52020-09-14 11:33:47 -04001673 while (fErrorCount == 0) {
1674 bool madeChanges = false;
John Stiles7954d6c2020-09-01 10:53:02 -04001675
Ethan Nicholas34b19c52020-09-14 11:33:47 -04001676 // Scan and optimize based on the control-flow graph for each function.
1677 for (ProgramElement& element : program) {
1678 if (element.is<FunctionDefinition>()) {
1679 madeChanges |= this->scanCFG(element.as<FunctionDefinition>());
1680 }
1681 }
1682
1683 // Perform inline-candidate analysis and inline any functions deemed suitable.
John Stiles910845f2020-09-18 15:41:07 -04001684 if (program.fSettings.fInline) {
1685 madeChanges |= fInliner.analyze(program);
1686 }
Ethan Nicholas34b19c52020-09-14 11:33:47 -04001687
1688 // Remove dead functions. We wait until after analysis so that we still report errors,
1689 // even in unused code.
1690 if (program.fSettings.fRemoveDeadFunctions) {
1691 program.fElements.erase(
1692 std::remove_if(program.fElements.begin(),
1693 program.fElements.end(),
1694 [&](const std::unique_ptr<ProgramElement>& element) {
1695 if (!element->is<FunctionDefinition>()) {
1696 return false;
1697 }
1698 const auto& fn = element->as<FunctionDefinition>();
1699 bool dead = fn.fDeclaration.fCallCount == 0 &&
1700 fn.fDeclaration.fName != "main";
1701 madeChanges |= dead;
1702 return dead;
1703 }),
1704 program.fElements.end());
1705 }
1706
1707 if (program.fKind != Program::kFragmentProcessor_Kind) {
1708 // Remove dead variables.
John Stileseadfc3b2020-09-02 14:12:41 -04001709 for (ProgramElement& element : program) {
Ethan Nicholas34b19c52020-09-14 11:33:47 -04001710 if (!element.is<VarDeclarations>()) {
1711 continue;
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001712 }
Ethan Nicholas34b19c52020-09-14 11:33:47 -04001713 VarDeclarations& vars = element.as<VarDeclarations>();
1714 vars.fVars.erase(
1715 std::remove_if(vars.fVars.begin(), vars.fVars.end(),
1716 [&](const std::unique_ptr<Statement>& stmt) {
1717 bool dead = stmt->as<VarDeclaration>().fVar->dead();
John Stiles73a6bff2020-09-09 13:40:37 -04001718 madeChanges |= dead;
1719 return dead;
1720 }),
Ethan Nicholas34b19c52020-09-14 11:33:47 -04001721 vars.fVars.end());
John Stiles73a6bff2020-09-09 13:40:37 -04001722 }
1723
Ethan Nicholas34b19c52020-09-14 11:33:47 -04001724 // Remove empty variable declarations with no variables left inside of them.
1725 program.fElements.erase(
1726 std::remove_if(program.fElements.begin(), program.fElements.end(),
1727 [&](const std::unique_ptr<ProgramElement>& element) {
1728 if (!element->is<VarDeclarations>()) {
1729 return false;
1730 }
1731 bool dead = element->as<VarDeclarations>().fVars.empty();
1732 madeChanges |= dead;
1733 return dead;
1734 }),
1735 program.fElements.end());
1736 }
John Stiles73a6bff2020-09-09 13:40:37 -04001737
Ethan Nicholas34b19c52020-09-14 11:33:47 -04001738 if (!madeChanges) {
1739 break;
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001740 }
Ethan Nicholas00543112018-07-31 09:44:36 -04001741 }
1742 return fErrorCount == 0;
1743}
1744
Brian Osmanfb32ddf2019-06-18 10:14:20 -04001745#if defined(SKSL_STANDALONE) || SK_SUPPORT_GPU
1746
Ethan Nicholas00543112018-07-31 09:44:36 -04001747bool Compiler::toSPIRV(Program& program, OutputStream& out) {
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001748#ifdef SK_ENABLE_SPIRV_VALIDATION
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001749 StringStream buffer;
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001750 fSource = program.fSource.get();
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001751 SPIRVCodeGenerator cg(fContext.get(), &program, this, &buffer);
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001752 bool result = cg.generateCode();
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001753 fSource = nullptr;
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001754 if (result) {
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001755 spvtools::SpirvTools tools(SPV_ENV_VULKAN_1_0);
Ethan Nicholas762466e2017-06-29 10:03:38 -04001756 const String& data = buffer.str();
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001757 SkASSERT(0 == data.size() % 4);
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001758 auto dumpmsg = [](spv_message_level_t, const char*, const spv_position_t&, const char* m) {
1759 SkDebugf("SPIR-V validation error: %s\n", m);
1760 };
1761 tools.SetMessageConsumer(dumpmsg);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001762 // Verify that the SPIR-V we produced is valid. If this SkASSERT fails, check the logs prior
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001763 // to the failure to see the validation errors.
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001764 SkAssertResult(tools.Validate((const uint32_t*) data.c_str(), data.size() / 4));
Ethan Nicholas762466e2017-06-29 10:03:38 -04001765 out.write(data.c_str(), data.size());
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001766 }
1767#else
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001768 fSource = program.fSource.get();
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001769 SPIRVCodeGenerator cg(fContext.get(), &program, this, &out);
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001770 bool result = cg.generateCode();
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001771 fSource = nullptr;
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001772#endif
Ethan Nicholasce33f102016-12-09 17:22:59 -05001773 return result;
1774}
1775
Ethan Nicholas00543112018-07-31 09:44:36 -04001776bool Compiler::toSPIRV(Program& program, String* out) {
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001777 StringStream buffer;
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001778 bool result = this->toSPIRV(program, buffer);
1779 if (result) {
Ethan Nicholas762466e2017-06-29 10:03:38 -04001780 *out = buffer.str();
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001781 }
1782 return result;
1783}
1784
Ethan Nicholas00543112018-07-31 09:44:36 -04001785bool Compiler::toGLSL(Program& program, OutputStream& out) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001786 fSource = program.fSource.get();
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001787 GLSLCodeGenerator cg(fContext.get(), &program, this, &out);
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001788 bool result = cg.generateCode();
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001789 fSource = nullptr;
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001790 return result;
1791}
1792
Ethan Nicholas00543112018-07-31 09:44:36 -04001793bool Compiler::toGLSL(Program& program, String* out) {
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001794 StringStream buffer;
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001795 bool result = this->toGLSL(program, buffer);
1796 if (result) {
Ethan Nicholas762466e2017-06-29 10:03:38 -04001797 *out = buffer.str();
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001798 }
1799 return result;
1800}
1801
Brian Osmanc0243912020-02-19 15:35:26 -05001802bool Compiler::toHLSL(Program& program, String* out) {
1803 String spirv;
1804 if (!this->toSPIRV(program, &spirv)) {
1805 return false;
1806 }
1807
1808 return SPIRVtoHLSL(spirv, out);
1809}
1810
Ethan Nicholas00543112018-07-31 09:44:36 -04001811bool Compiler::toMetal(Program& program, OutputStream& out) {
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001812 MetalCodeGenerator cg(fContext.get(), &program, this, &out);
Ethan Nicholascc305772017-10-13 16:17:45 -04001813 bool result = cg.generateCode();
Ethan Nicholascc305772017-10-13 16:17:45 -04001814 return result;
1815}
1816
Ethan Nicholas00543112018-07-31 09:44:36 -04001817bool Compiler::toMetal(Program& program, String* out) {
Timothy Liangb8eeb802018-07-23 16:46:16 -04001818 StringStream buffer;
1819 bool result = this->toMetal(program, buffer);
1820 if (result) {
1821 *out = buffer.str();
1822 }
1823 return result;
1824}
1825
Ethan Nicholas2a479a52020-08-18 16:29:45 -04001826#if defined(SKSL_STANDALONE) || defined(GR_TEST_UTILS)
Ethan Nicholas00543112018-07-31 09:44:36 -04001827bool Compiler::toCPP(Program& program, String name, OutputStream& out) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001828 fSource = program.fSource.get();
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001829 CPPCodeGenerator cg(fContext.get(), &program, this, name, &out);
Ethan Nicholas762466e2017-06-29 10:03:38 -04001830 bool result = cg.generateCode();
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001831 fSource = nullptr;
Ethan Nicholas762466e2017-06-29 10:03:38 -04001832 return result;
1833}
1834
Ethan Nicholas00543112018-07-31 09:44:36 -04001835bool Compiler::toH(Program& program, String name, OutputStream& out) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001836 fSource = program.fSource.get();
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001837 HCodeGenerator cg(fContext.get(), &program, this, name, &out);
Ethan Nicholas762466e2017-06-29 10:03:38 -04001838 bool result = cg.generateCode();
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001839 fSource = nullptr;
Ethan Nicholas00543112018-07-31 09:44:36 -04001840 return result;
1841}
Ethan Nicholas2a479a52020-08-18 16:29:45 -04001842#endif // defined(SKSL_STANDALONE) || defined(GR_TEST_UTILS)
Ethan Nicholas00543112018-07-31 09:44:36 -04001843
Ethan Nicholas2a479a52020-08-18 16:29:45 -04001844#endif // defined(SKSL_STANDALONE) || SK_SUPPORT_GPU
Brian Osman2e29ab52019-09-20 12:19:11 -04001845
1846#if !defined(SKSL_STANDALONE) && SK_SUPPORT_GPU
Brian Osmana4b91692020-08-10 14:26:16 -04001847bool Compiler::toPipelineStage(Program& program, PipelineStageArgs* outArgs) {
Ethan Nicholas00543112018-07-31 09:44:36 -04001848 fSource = program.fSource.get();
1849 StringStream buffer;
Brian Osman300fe1d2020-01-23 15:42:43 -05001850 PipelineStageCodeGenerator cg(fContext.get(), &program, this, &buffer, outArgs);
Ethan Nicholas00543112018-07-31 09:44:36 -04001851 bool result = cg.generateCode();
1852 fSource = nullptr;
1853 if (result) {
Brian Osman107c6662019-12-30 15:02:30 -05001854 outArgs->fCode = buffer.str();
Ethan Nicholas00543112018-07-31 09:44:36 -04001855 }
Ethan Nicholas762466e2017-06-29 10:03:38 -04001856 return result;
1857}
Brian Osmanfb32ddf2019-06-18 10:14:20 -04001858#endif
1859
Ethan Nicholas0e9401d2019-03-21 11:05:37 -04001860std::unique_ptr<ByteCode> Compiler::toByteCode(Program& program) {
Mike Klein853d4ed2020-08-20 00:41:00 +00001861#if defined(SK_ENABLE_SKSL_INTERPRETER)
Brian Osman808f0212020-01-21 15:36:47 -05001862 fSource = program.fSource.get();
Ethan Nicholas0e9401d2019-03-21 11:05:37 -04001863 std::unique_ptr<ByteCode> result(new ByteCode());
Brian Osmanb08cc022020-04-02 11:38:40 -04001864 ByteCodeGenerator cg(fContext.get(), &program, this, result.get());
1865 bool success = cg.generateCode();
1866 fSource = nullptr;
1867 if (success) {
Ethan Nicholas0e9401d2019-03-21 11:05:37 -04001868 return result;
1869 }
Mike Klein853d4ed2020-08-20 00:41:00 +00001870#else
1871 ABORT("ByteCode interpreter not enabled");
1872#endif
Ethan Nicholas0e9401d2019-03-21 11:05:37 -04001873 return nullptr;
1874}
1875
Brian Osman401a0092020-09-10 14:47:24 -04001876const char* Compiler::OperatorName(Token::Kind op) {
1877 switch (op) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001878 case Token::Kind::TK_PLUS: return "+";
1879 case Token::Kind::TK_MINUS: return "-";
1880 case Token::Kind::TK_STAR: return "*";
1881 case Token::Kind::TK_SLASH: return "/";
1882 case Token::Kind::TK_PERCENT: return "%";
1883 case Token::Kind::TK_SHL: return "<<";
1884 case Token::Kind::TK_SHR: return ">>";
1885 case Token::Kind::TK_LOGICALNOT: return "!";
1886 case Token::Kind::TK_LOGICALAND: return "&&";
1887 case Token::Kind::TK_LOGICALOR: return "||";
1888 case Token::Kind::TK_LOGICALXOR: return "^^";
1889 case Token::Kind::TK_BITWISENOT: return "~";
1890 case Token::Kind::TK_BITWISEAND: return "&";
1891 case Token::Kind::TK_BITWISEOR: return "|";
1892 case Token::Kind::TK_BITWISEXOR: return "^";
1893 case Token::Kind::TK_EQ: return "=";
1894 case Token::Kind::TK_EQEQ: return "==";
1895 case Token::Kind::TK_NEQ: return "!=";
1896 case Token::Kind::TK_LT: return "<";
1897 case Token::Kind::TK_GT: return ">";
1898 case Token::Kind::TK_LTEQ: return "<=";
1899 case Token::Kind::TK_GTEQ: return ">=";
1900 case Token::Kind::TK_PLUSEQ: return "+=";
1901 case Token::Kind::TK_MINUSEQ: return "-=";
1902 case Token::Kind::TK_STAREQ: return "*=";
1903 case Token::Kind::TK_SLASHEQ: return "/=";
1904 case Token::Kind::TK_PERCENTEQ: return "%=";
1905 case Token::Kind::TK_SHLEQ: return "<<=";
1906 case Token::Kind::TK_SHREQ: return ">>=";
1907 case Token::Kind::TK_LOGICALANDEQ: return "&&=";
1908 case Token::Kind::TK_LOGICALOREQ: return "||=";
1909 case Token::Kind::TK_LOGICALXOREQ: return "^^=";
1910 case Token::Kind::TK_BITWISEANDEQ: return "&=";
1911 case Token::Kind::TK_BITWISEOREQ: return "|=";
1912 case Token::Kind::TK_BITWISEXOREQ: return "^=";
1913 case Token::Kind::TK_PLUSPLUS: return "++";
1914 case Token::Kind::TK_MINUSMINUS: return "--";
1915 case Token::Kind::TK_COMMA: return ",";
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001916 default:
Brian Osman401a0092020-09-10 14:47:24 -04001917 ABORT("unsupported operator: %d\n", (int) op);
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001918 }
1919}
1920
1921
1922bool Compiler::IsAssignment(Token::Kind op) {
1923 switch (op) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001924 case Token::Kind::TK_EQ: // fall through
1925 case Token::Kind::TK_PLUSEQ: // fall through
1926 case Token::Kind::TK_MINUSEQ: // fall through
1927 case Token::Kind::TK_STAREQ: // fall through
1928 case Token::Kind::TK_SLASHEQ: // fall through
1929 case Token::Kind::TK_PERCENTEQ: // fall through
1930 case Token::Kind::TK_SHLEQ: // fall through
1931 case Token::Kind::TK_SHREQ: // fall through
1932 case Token::Kind::TK_BITWISEOREQ: // fall through
1933 case Token::Kind::TK_BITWISEXOREQ: // fall through
1934 case Token::Kind::TK_BITWISEANDEQ: // fall through
1935 case Token::Kind::TK_LOGICALOREQ: // fall through
1936 case Token::Kind::TK_LOGICALXOREQ: // fall through
1937 case Token::Kind::TK_LOGICALANDEQ:
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001938 return true;
1939 default:
1940 return false;
1941 }
1942}
1943
Brian Osman401a0092020-09-10 14:47:24 -04001944Token::Kind Compiler::RemoveAssignment(Token::Kind op) {
1945 switch (op) {
1946 case Token::Kind::TK_PLUSEQ: return Token::Kind::TK_PLUS;
1947 case Token::Kind::TK_MINUSEQ: return Token::Kind::TK_MINUS;
1948 case Token::Kind::TK_STAREQ: return Token::Kind::TK_STAR;
1949 case Token::Kind::TK_SLASHEQ: return Token::Kind::TK_SLASH;
1950 case Token::Kind::TK_PERCENTEQ: return Token::Kind::TK_PERCENT;
1951 case Token::Kind::TK_SHLEQ: return Token::Kind::TK_SHL;
1952 case Token::Kind::TK_SHREQ: return Token::Kind::TK_SHR;
1953 case Token::Kind::TK_BITWISEOREQ: return Token::Kind::TK_BITWISEOR;
1954 case Token::Kind::TK_BITWISEXOREQ: return Token::Kind::TK_BITWISEXOR;
1955 case Token::Kind::TK_BITWISEANDEQ: return Token::Kind::TK_BITWISEAND;
1956 case Token::Kind::TK_LOGICALOREQ: return Token::Kind::TK_LOGICALOR;
1957 case Token::Kind::TK_LOGICALXOREQ: return Token::Kind::TK_LOGICALXOR;
1958 case Token::Kind::TK_LOGICALANDEQ: return Token::Kind::TK_LOGICALAND;
1959 default: return op;
1960 }
1961}
1962
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001963Position Compiler::position(int offset) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001964 SkASSERT(fSource);
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001965 int line = 1;
1966 int column = 1;
1967 for (int i = 0; i < offset; i++) {
1968 if ((*fSource)[i] == '\n') {
1969 ++line;
1970 column = 1;
1971 }
1972 else {
1973 ++column;
1974 }
1975 }
1976 return Position(line, column);
1977}
1978
1979void Compiler::error(int offset, String msg) {
ethannicholasb3058bd2016-07-01 08:22:01 -07001980 fErrorCount++;
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001981 Position pos = this->position(offset);
1982 fErrorText += "error: " + to_string(pos.fLine) + ": " + msg.c_str() + "\n";
ethannicholasb3058bd2016-07-01 08:22:01 -07001983}
1984
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001985String Compiler::errorText() {
Ethan Nicholas00543112018-07-31 09:44:36 -04001986 this->writeErrorCount();
1987 fErrorCount = 0;
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001988 String result = fErrorText;
ethannicholasb3058bd2016-07-01 08:22:01 -07001989 return result;
1990}
1991
1992void Compiler::writeErrorCount() {
1993 if (fErrorCount) {
1994 fErrorText += to_string(fErrorCount) + " error";
1995 if (fErrorCount > 1) {
1996 fErrorText += "s";
1997 }
1998 fErrorText += "\n";
1999 }
2000}
2001
John Stilesa6841be2020-08-06 14:11:56 -04002002} // namespace SkSL