blob: 0dde6ca21d4866ad6184624ca2598fa9eff31613 [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);
Brian Osman2b469eb2020-09-21 11:32:10 -040081 target->insertOrDie(f.fDeclaration.description(), std::move(element));
Brian Osman08f986d2020-05-13 17:06:46 -040082 iter = src->erase(iter);
Ethan Nicholasdb80f692019-11-22 14:06:12 -050083 break;
84 }
Ethan Nicholase6592142020-09-08 10:22:09 -040085 case ProgramElement::Kind::kEnum: {
John Stiles3dc0da62020-08-19 17:48:31 -040086 Enum& e = element->as<Enum>();
Brian Osman2b469eb2020-09-21 11:32:10 -040087 target->insertOrDie(e.fTypeName, std::move(element));
Brian Osman08f986d2020-05-13 17:06:46 -040088 iter = src->erase(iter);
Ethan Nicholasdb80f692019-11-22 14:06:12 -050089 break;
90 }
91 default:
Brian Osman2b469eb2020-09-21 11:32:10 -040092 // Unsupported element, leave it in the list.
93 ++iter;
94 break;
Ethan Nicholasdb80f692019-11-22 14:06:12 -050095 }
96 }
97}
98
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -040099Compiler::Compiler(Flags flags)
Brian Osman2b469eb2020-09-21 11:32:10 -0400100: fGPUIntrinsics(std::make_unique<IRIntrinsicMap>(/*parent=*/nullptr))
101, fInterpreterIntrinsics(std::make_unique<IRIntrinsicMap>(/*parent=*/nullptr))
John Stiles810c8cf2020-08-26 19:46:27 -0400102, fFlags(flags)
103, fContext(std::make_shared<Context>())
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -0400104, fErrorCount(0) {
Brian Osmaneac49832020-09-18 11:49:22 -0400105 fRootSymbolTable = std::make_shared<SymbolTable>(this);
John Stiles941fc712020-09-19 12:47:10 +0000106 fIRGenerator =
107 std::make_unique<IRGenerator>(fContext.get(), &fInliner, fRootSymbolTable, *this);
Brian Osmaneac49832020-09-18 11:49:22 -0400108 #define ADD_TYPE(t) fRootSymbolTable->addWithoutOwnership(fContext->f ## t ## _Type->fName, \
109 fContext->f ## t ## _Type.get())
ethannicholasb3058bd2016-07-01 08:22:01 -0700110 ADD_TYPE(Void);
111 ADD_TYPE(Float);
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400112 ADD_TYPE(Float2);
113 ADD_TYPE(Float3);
114 ADD_TYPE(Float4);
Ethan Nicholasdcba08e2017-08-02 10:52:54 -0400115 ADD_TYPE(Half);
116 ADD_TYPE(Half2);
117 ADD_TYPE(Half3);
118 ADD_TYPE(Half4);
ethannicholasb3058bd2016-07-01 08:22:01 -0700119 ADD_TYPE(Int);
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400120 ADD_TYPE(Int2);
121 ADD_TYPE(Int3);
122 ADD_TYPE(Int4);
ethannicholasb3058bd2016-07-01 08:22:01 -0700123 ADD_TYPE(UInt);
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400124 ADD_TYPE(UInt2);
125 ADD_TYPE(UInt3);
126 ADD_TYPE(UInt4);
Ethan Nicholasdcba08e2017-08-02 10:52:54 -0400127 ADD_TYPE(Short);
128 ADD_TYPE(Short2);
129 ADD_TYPE(Short3);
130 ADD_TYPE(Short4);
131 ADD_TYPE(UShort);
132 ADD_TYPE(UShort2);
133 ADD_TYPE(UShort3);
134 ADD_TYPE(UShort4);
Ruiqi Maob609e6d2018-07-17 10:19:38 -0400135 ADD_TYPE(Byte);
136 ADD_TYPE(Byte2);
137 ADD_TYPE(Byte3);
138 ADD_TYPE(Byte4);
139 ADD_TYPE(UByte);
140 ADD_TYPE(UByte2);
141 ADD_TYPE(UByte3);
142 ADD_TYPE(UByte4);
ethannicholasb3058bd2016-07-01 08:22:01 -0700143 ADD_TYPE(Bool);
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400144 ADD_TYPE(Bool2);
145 ADD_TYPE(Bool3);
146 ADD_TYPE(Bool4);
147 ADD_TYPE(Float2x2);
148 ADD_TYPE(Float2x3);
149 ADD_TYPE(Float2x4);
150 ADD_TYPE(Float3x2);
151 ADD_TYPE(Float3x3);
152 ADD_TYPE(Float3x4);
153 ADD_TYPE(Float4x2);
154 ADD_TYPE(Float4x3);
155 ADD_TYPE(Float4x4);
Ethan Nicholasdcba08e2017-08-02 10:52:54 -0400156 ADD_TYPE(Half2x2);
157 ADD_TYPE(Half2x3);
158 ADD_TYPE(Half2x4);
159 ADD_TYPE(Half3x2);
160 ADD_TYPE(Half3x3);
161 ADD_TYPE(Half3x4);
162 ADD_TYPE(Half4x2);
163 ADD_TYPE(Half4x3);
164 ADD_TYPE(Half4x4);
ethannicholasb3058bd2016-07-01 08:22:01 -0700165 ADD_TYPE(GenType);
Ethan Nicholasdcba08e2017-08-02 10:52:54 -0400166 ADD_TYPE(GenHType);
ethannicholasb3058bd2016-07-01 08:22:01 -0700167 ADD_TYPE(GenIType);
168 ADD_TYPE(GenUType);
169 ADD_TYPE(GenBType);
170 ADD_TYPE(Mat);
171 ADD_TYPE(Vec);
172 ADD_TYPE(GVec);
173 ADD_TYPE(GVec2);
174 ADD_TYPE(GVec3);
175 ADD_TYPE(GVec4);
Ethan Nicholasdcba08e2017-08-02 10:52:54 -0400176 ADD_TYPE(HVec);
ethannicholasb3058bd2016-07-01 08:22:01 -0700177 ADD_TYPE(IVec);
178 ADD_TYPE(UVec);
Ethan Nicholasdcba08e2017-08-02 10:52:54 -0400179 ADD_TYPE(SVec);
180 ADD_TYPE(USVec);
Ruiqi Maob609e6d2018-07-17 10:19:38 -0400181 ADD_TYPE(ByteVec);
182 ADD_TYPE(UByteVec);
ethannicholasb3058bd2016-07-01 08:22:01 -0700183 ADD_TYPE(BVec);
184
185 ADD_TYPE(Sampler1D);
186 ADD_TYPE(Sampler2D);
187 ADD_TYPE(Sampler3D);
ethannicholas5961bc92016-10-12 06:39:56 -0700188 ADD_TYPE(SamplerExternalOES);
ethannicholasb3058bd2016-07-01 08:22:01 -0700189 ADD_TYPE(SamplerCube);
190 ADD_TYPE(Sampler2DRect);
191 ADD_TYPE(Sampler1DArray);
192 ADD_TYPE(Sampler2DArray);
193 ADD_TYPE(SamplerCubeArray);
194 ADD_TYPE(SamplerBuffer);
195 ADD_TYPE(Sampler2DMS);
196 ADD_TYPE(Sampler2DMSArray);
197
Brian Salomonbf7b6202016-11-11 16:08:03 -0500198 ADD_TYPE(ISampler2D);
199
Brian Salomon2a51de82016-11-16 12:06:01 -0500200 ADD_TYPE(Image2D);
201 ADD_TYPE(IImage2D);
202
Greg Daniel64773e62016-11-22 09:44:03 -0500203 ADD_TYPE(SubpassInput);
204 ADD_TYPE(SubpassInputMS);
205
ethannicholasb3058bd2016-07-01 08:22:01 -0700206 ADD_TYPE(GSampler1D);
207 ADD_TYPE(GSampler2D);
208 ADD_TYPE(GSampler3D);
209 ADD_TYPE(GSamplerCube);
210 ADD_TYPE(GSampler2DRect);
211 ADD_TYPE(GSampler1DArray);
212 ADD_TYPE(GSampler2DArray);
213 ADD_TYPE(GSamplerCubeArray);
214 ADD_TYPE(GSamplerBuffer);
215 ADD_TYPE(GSampler2DMS);
216 ADD_TYPE(GSampler2DMSArray);
217
218 ADD_TYPE(Sampler1DShadow);
219 ADD_TYPE(Sampler2DShadow);
220 ADD_TYPE(SamplerCubeShadow);
221 ADD_TYPE(Sampler2DRectShadow);
222 ADD_TYPE(Sampler1DArrayShadow);
223 ADD_TYPE(Sampler2DArrayShadow);
224 ADD_TYPE(SamplerCubeArrayShadow);
225 ADD_TYPE(GSampler2DArrayShadow);
226 ADD_TYPE(GSamplerCubeArrayShadow);
Ethan Nicholasc9472af2017-10-10 16:30:21 -0400227 ADD_TYPE(FragmentProcessor);
Stephen Whiteff5d7a22019-07-26 17:42:06 -0400228 ADD_TYPE(Sampler);
229 ADD_TYPE(Texture2D);
ethannicholasb3058bd2016-07-01 08:22:01 -0700230
Brian Osman28590d52020-03-23 16:59:08 -0400231 StringFragment fpAliasName("shader");
Brian Osmaneac49832020-09-18 11:49:22 -0400232 fRootSymbolTable->addWithoutOwnership(fpAliasName, fContext->fFragmentProcessor_Type.get());
Brian Osman28590d52020-03-23 16:59:08 -0400233
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700234 StringFragment skCapsName("sk_Caps");
Brian Osmaneac49832020-09-18 11:49:22 -0400235 fRootSymbolTable->add(
John Stiles311dd9d2020-08-13 17:09:29 -0400236 skCapsName,
237 std::make_unique<Variable>(/*offset=*/-1, Modifiers(), skCapsName,
Ethan Nicholas30d30222020-09-11 12:27:26 -0400238 fContext->fSkCaps_Type.get(), Variable::kGlobal_Storage));
Ethan Nicholas3605ace2016-11-21 15:59:48 -0500239
John Stiles810c8cf2020-08-26 19:46:27 -0400240 fIRGenerator->fIntrinsics = fGPUIntrinsics.get();
Ethan Nicholasdb80f692019-11-22 14:06:12 -0500241 std::vector<std::unique_ptr<ProgramElement>> gpuIntrinsics;
Brian Osmandd496172020-08-08 08:17:18 -0400242#if SKSL_STANDALONE
Brian Osmaneac49832020-09-18 11:49:22 -0400243 this->processIncludeFile(Program::kFragment_Kind, SKSL_GPU_INCLUDE, fRootSymbolTable,
244 &gpuIntrinsics, &fGpuSymbolTable);
Ethan Nicholasb33fa3f2020-08-06 13:00:19 -0400245 this->processIncludeFile(Program::kVertex_Kind, SKSL_VERT_INCLUDE, fGpuSymbolTable,
246 &fVertexInclude, &fVertexSymbolTable);
247 this->processIncludeFile(Program::kFragment_Kind, SKSL_FRAG_INCLUDE, fGpuSymbolTable,
248 &fFragmentInclude, &fFragmentSymbolTable);
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400249#else
250 {
Brian Osmaneac49832020-09-18 11:49:22 -0400251 Rehydrator rehydrator(fContext.get(), fRootSymbolTable, this, SKSL_INCLUDE_sksl_gpu,
252 SKSL_INCLUDE_sksl_gpu_LENGTH);
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400253 fGpuSymbolTable = rehydrator.symbolTable();
254 gpuIntrinsics = rehydrator.elements();
255 }
256 {
257 Rehydrator rehydrator(fContext.get(), fGpuSymbolTable, this, SKSL_INCLUDE_sksl_vert,
Brian Osmaneac49832020-09-18 11:49:22 -0400258 SKSL_INCLUDE_sksl_vert_LENGTH);
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400259 fVertexSymbolTable = rehydrator.symbolTable();
260 fVertexInclude = rehydrator.elements();
261 }
262 {
263 Rehydrator rehydrator(fContext.get(), fGpuSymbolTable, this, SKSL_INCLUDE_sksl_frag,
Brian Osmaneac49832020-09-18 11:49:22 -0400264 SKSL_INCLUDE_sksl_frag_LENGTH);
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400265 fFragmentSymbolTable = rehydrator.symbolTable();
266 fFragmentInclude = rehydrator.elements();
267 }
268#endif
John Stiles810c8cf2020-08-26 19:46:27 -0400269 grab_intrinsics(&gpuIntrinsics, fGPUIntrinsics.get());
Brian Osman2b469eb2020-09-21 11:32:10 -0400270 SkASSERT(gpuIntrinsics.empty());
ethannicholasb3058bd2016-07-01 08:22:01 -0700271}
272
John Stiles656427a2020-08-27 15:26:26 -0400273Compiler::~Compiler() {}
ethannicholasb3058bd2016-07-01 08:22:01 -0700274
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400275void Compiler::loadGeometryIntrinsics() {
276 if (fGeometrySymbolTable) {
277 return;
278 }
Brian Osmandd496172020-08-08 08:17:18 -0400279 #if !SKSL_STANDALONE
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400280 {
281 Rehydrator rehydrator(fContext.get(), fGpuSymbolTable, this, SKSL_INCLUDE_sksl_geom,
282 SKSL_INCLUDE_sksl_geom_LENGTH);
283 fGeometrySymbolTable = rehydrator.symbolTable();
284 fGeometryInclude = rehydrator.elements();
285 }
286 #else
Ethan Nicholasb33fa3f2020-08-06 13:00:19 -0400287 this->processIncludeFile(Program::kGeometry_Kind, SKSL_GEOM_INCLUDE, fGpuSymbolTable,
288 &fGeometryInclude, &fGeometrySymbolTable);
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400289 #endif
290}
291
292void Compiler::loadPipelineIntrinsics() {
293 if (fPipelineSymbolTable) {
294 return;
295 }
Brian Osmandd496172020-08-08 08:17:18 -0400296 #if !SKSL_STANDALONE
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400297 {
298 Rehydrator rehydrator(fContext.get(), fGpuSymbolTable, this,
299 SKSL_INCLUDE_sksl_pipeline,
300 SKSL_INCLUDE_sksl_pipeline_LENGTH);
301 fPipelineSymbolTable = rehydrator.symbolTable();
302 fPipelineInclude = rehydrator.elements();
303 }
304 #else
305 this->processIncludeFile(Program::kPipelineStage_Kind, SKSL_PIPELINE_INCLUDE,
Ethan Nicholasb33fa3f2020-08-06 13:00:19 -0400306 fGpuSymbolTable, &fPipelineInclude, &fPipelineSymbolTable);
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400307 #endif
308}
309
310void Compiler::loadInterpreterIntrinsics() {
311 if (fInterpreterSymbolTable) {
312 return;
313 }
Brian Osmaneac49832020-09-18 11:49:22 -0400314 std::vector<std::unique_ptr<ProgramElement>> interpIntrinsics;
Brian Osmandd496172020-08-08 08:17:18 -0400315 #if !SKSL_STANDALONE
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400316 {
Brian Osmaneac49832020-09-18 11:49:22 -0400317 Rehydrator rehydrator(fContext.get(), fRootSymbolTable, this,
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400318 SKSL_INCLUDE_sksl_interp,
319 SKSL_INCLUDE_sksl_interp_LENGTH);
320 fInterpreterSymbolTable = rehydrator.symbolTable();
Brian Osmaneac49832020-09-18 11:49:22 -0400321 interpIntrinsics = rehydrator.elements();
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400322 }
323 #else
324 this->processIncludeFile(Program::kGeneric_Kind, SKSL_INTERP_INCLUDE,
Brian Osmaneac49832020-09-18 11:49:22 -0400325 fIRGenerator->fSymbolTable, &interpIntrinsics,
Ethan Nicholasb33fa3f2020-08-06 13:00:19 -0400326 &fInterpreterSymbolTable);
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400327 #endif
Brian Osmaneac49832020-09-18 11:49:22 -0400328 grab_intrinsics(&interpIntrinsics, fInterpreterIntrinsics.get());
Brian Osman2b469eb2020-09-21 11:32:10 -0400329 SkASSERT(interpIntrinsics.empty());
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;
Ethan Nicholasa11035b2019-11-26 16:27:47 -0500354#if !defined(SKSL_STANDALONE) & SK_SUPPORT_GPU
355 GrContextOptions opts;
356 GrShaderCaps caps(opts);
357 settings.fCaps = &caps;
358#endif
John Stiles881a10c2020-09-19 10:13:24 -0400359 SkASSERT(fIRGenerator->fCanInline);
360 fIRGenerator->fCanInline = false;
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400361 fIRGenerator->start(&settings, nullptr, true);
Ethan Nicholasb33fa3f2020-08-06 13:00:19 -0400362 fIRGenerator->convertProgram(kind, source->c_str(), source->length(), outElements);
John Stiles881a10c2020-09-19 10:13:24 -0400363 fIRGenerator->fCanInline = true;
Ethan Nicholas8da1e652019-05-24 11:01:59 -0400364 if (this->fErrorCount) {
365 printf("Unexpected errors: %s\n", this->fErrorText.c_str());
366 }
367 SkASSERT(!fErrorCount);
Ethan Nicholas8da1e652019-05-24 11:01:59 -0400368 *outSymbolTable = fIRGenerator->fSymbolTable;
Ethan Nicholasa11035b2019-11-26 16:27:47 -0500369#ifdef SK_DEBUG
370 fSource = nullptr;
371#endif
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400372 fIRGenerator->fSymbolTable = std::move(old);
Ethan Nicholas8da1e652019-05-24 11:01:59 -0400373}
374
ethannicholas22f939e2016-10-13 13:25:34 -0700375// add the definition created by assigning to the lvalue to the definition set
Ethan Nicholas86a43402017-01-19 13:32:00 -0500376void Compiler::addDefinition(const Expression* lvalue, std::unique_ptr<Expression>* expr,
377 DefinitionMap* definitions) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400378 switch (lvalue->kind()) {
379 case Expression::Kind::kVariableReference: {
John Stilesa5a97b42020-08-18 11:19:07 -0400380 const Variable& var = lvalue->as<VariableReference>().fVariable;
ethannicholas22f939e2016-10-13 13:25:34 -0700381 if (var.fStorage == Variable::kLocal_Storage) {
382 (*definitions)[&var] = expr;
383 }
384 break;
385 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400386 case Expression::Kind::kSwizzle:
ethannicholas22f939e2016-10-13 13:25:34 -0700387 // We consider the variable written to as long as at least some of its components have
388 // been written to. This will lead to some false negatives (we won't catch it if you
389 // write to foo.x and then read foo.y), but being stricter could lead to false positives
Mike Klein6ad99092016-10-26 10:35:22 -0400390 // (we write to foo.x, and then pass foo to a function which happens to only read foo.x,
391 // 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 -0700392 // more complicated whole-program analysis. This is probably good enough.
John Stilesa5a97b42020-08-18 11:19:07 -0400393 this->addDefinition(lvalue->as<Swizzle>().fBase.get(),
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400394 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
ethannicholas22f939e2016-10-13 13:25:34 -0700395 definitions);
396 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400397 case Expression::Kind::kIndex:
ethannicholas22f939e2016-10-13 13:25:34 -0700398 // see comments in Swizzle
John Stilesa5a97b42020-08-18 11:19:07 -0400399 this->addDefinition(lvalue->as<IndexExpression>().fBase.get(),
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400400 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
ethannicholas22f939e2016-10-13 13:25:34 -0700401 definitions);
402 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400403 case Expression::Kind::kFieldAccess:
ethannicholas22f939e2016-10-13 13:25:34 -0700404 // see comments in Swizzle
John Stilesa5a97b42020-08-18 11:19:07 -0400405 this->addDefinition(lvalue->as<FieldAccess>().fBase.get(),
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400406 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
ethannicholas22f939e2016-10-13 13:25:34 -0700407 definitions);
408 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400409 case Expression::Kind::kTernary:
Ethan Nicholasa583b812018-01-18 13:32:11 -0500410 // To simplify analysis, we just pretend that we write to both sides of the ternary.
411 // This allows for false positives (meaning we fail to detect that a variable might not
412 // have been assigned), but is preferable to false negatives.
John Stilesa5a97b42020-08-18 11:19:07 -0400413 this->addDefinition(lvalue->as<TernaryExpression>().fIfTrue.get(),
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400414 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
Ethan Nicholasa583b812018-01-18 13:32:11 -0500415 definitions);
John Stilesa5a97b42020-08-18 11:19:07 -0400416 this->addDefinition(lvalue->as<TernaryExpression>().fIfFalse.get(),
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400417 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
Ethan Nicholasa583b812018-01-18 13:32:11 -0500418 definitions);
419 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400420 case Expression::Kind::kExternalValue:
Ethan Nicholas91164d12019-05-15 15:29:54 -0400421 break;
ethannicholas22f939e2016-10-13 13:25:34 -0700422 default:
423 // not an lvalue, can't happen
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400424 SkASSERT(false);
ethannicholas22f939e2016-10-13 13:25:34 -0700425 }
426}
427
428// add local variables defined by this node to the set
Mike Klein6ad99092016-10-26 10:35:22 -0400429void Compiler::addDefinitions(const BasicBlock::Node& node,
Ethan Nicholas86a43402017-01-19 13:32:00 -0500430 DefinitionMap* definitions) {
ethannicholas22f939e2016-10-13 13:25:34 -0700431 switch (node.fKind) {
432 case BasicBlock::Node::kExpression_Kind: {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400433 SkASSERT(node.expression());
John Stilesa5a97b42020-08-18 11:19:07 -0400434 Expression* expr = node.expression()->get();
Ethan Nicholase6592142020-09-08 10:22:09 -0400435 switch (expr->kind()) {
436 case Expression::Kind::kBinary: {
John Stilesa5a97b42020-08-18 11:19:07 -0400437 BinaryExpression* b = &expr->as<BinaryExpression>();
Ethan Nicholasbf66ffb2020-09-16 22:05:10 +0000438 if (b->fOperator == Token::Kind::TK_EQ) {
439 this->addDefinition(b->fLeft.get(), &b->fRight, definitions);
440 } else if (Compiler::IsAssignment(b->fOperator)) {
Ethan Nicholas86a43402017-01-19 13:32:00 -0500441 this->addDefinition(
Ethan Nicholasbf66ffb2020-09-16 22:05:10 +0000442 b->fLeft.get(),
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400443 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
444 definitions);
Ethan Nicholas86a43402017-01-19 13:32:00 -0500445
446 }
447 break;
ethannicholas22f939e2016-10-13 13:25:34 -0700448 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400449 case Expression::Kind::kFunctionCall: {
John Stilesa5a97b42020-08-18 11:19:07 -0400450 const FunctionCall& c = expr->as<FunctionCall>();
Ethan Nicholasc6a19f12018-03-29 16:46:56 -0400451 for (size_t i = 0; i < c.fFunction.fParameters.size(); ++i) {
452 if (c.fFunction.fParameters[i]->fModifiers.fFlags & Modifiers::kOut_Flag) {
453 this->addDefinition(
454 c.fArguments[i].get(),
455 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
456 definitions);
457 }
458 }
459 break;
460 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400461 case Expression::Kind::kPrefix: {
John Stilesa5a97b42020-08-18 11:19:07 -0400462 const PrefixExpression* p = &expr->as<PrefixExpression>();
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400463 if (p->fOperator == Token::Kind::TK_MINUSMINUS ||
464 p->fOperator == Token::Kind::TK_PLUSPLUS) {
Ethan Nicholas86a43402017-01-19 13:32:00 -0500465 this->addDefinition(
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400466 p->fOperand.get(),
467 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
468 definitions);
Ethan Nicholas86a43402017-01-19 13:32:00 -0500469 }
470 break;
471 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400472 case Expression::Kind::kPostfix: {
John Stilesa5a97b42020-08-18 11:19:07 -0400473 const PostfixExpression* p = &expr->as<PostfixExpression>();
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400474 if (p->fOperator == Token::Kind::TK_MINUSMINUS ||
475 p->fOperator == Token::Kind::TK_PLUSPLUS) {
Ethan Nicholas86a43402017-01-19 13:32:00 -0500476 this->addDefinition(
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400477 p->fOperand.get(),
478 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
479 definitions);
Ethan Nicholas86a43402017-01-19 13:32:00 -0500480 }
481 break;
482 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400483 case Expression::Kind::kVariableReference: {
John Stilesa5a97b42020-08-18 11:19:07 -0400484 const VariableReference* v = &expr->as<VariableReference>();
Ethan Nicholascb670962017-04-20 19:31:52 -0400485 if (v->fRefKind != VariableReference::kRead_RefKind) {
486 this->addDefinition(
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400487 v,
488 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
489 definitions);
Ethan Nicholascb670962017-04-20 19:31:52 -0400490 }
John Stiles30212b72020-06-11 17:55:07 -0400491 break;
Ethan Nicholascb670962017-04-20 19:31:52 -0400492 }
Ethan Nicholas86a43402017-01-19 13:32:00 -0500493 default:
494 break;
ethannicholas22f939e2016-10-13 13:25:34 -0700495 }
496 break;
497 }
498 case BasicBlock::Node::kStatement_Kind: {
John Stilesa5a97b42020-08-18 11:19:07 -0400499 Statement* stmt = node.statement()->get();
Ethan Nicholase6592142020-09-08 10:22:09 -0400500 if (stmt->kind() == Statement::Kind::kVarDeclaration) {
John Stilesa5a97b42020-08-18 11:19:07 -0400501 VarDeclaration& vd = stmt->as<VarDeclaration>();
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000502 if (vd.fValue) {
503 (*definitions)[vd.fVar] = &vd.fValue;
ethannicholas22f939e2016-10-13 13:25:34 -0700504 }
505 }
506 break;
507 }
508 }
509}
510
511void Compiler::scanCFG(CFG* cfg, BlockId blockId, std::set<BlockId>* workList) {
512 BasicBlock& block = cfg->fBlocks[blockId];
513
514 // compute definitions after this block
Ethan Nicholas86a43402017-01-19 13:32:00 -0500515 DefinitionMap after = block.fBefore;
ethannicholas22f939e2016-10-13 13:25:34 -0700516 for (const BasicBlock::Node& n : block.fNodes) {
517 this->addDefinitions(n, &after);
518 }
519
520 // propagate definitions to exits
521 for (BlockId exitId : block.fExits) {
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400522 if (exitId == blockId) {
523 continue;
524 }
ethannicholas22f939e2016-10-13 13:25:34 -0700525 BasicBlock& exit = cfg->fBlocks[exitId];
526 for (const auto& pair : after) {
Ethan Nicholas86a43402017-01-19 13:32:00 -0500527 std::unique_ptr<Expression>* e1 = pair.second;
528 auto found = exit.fBefore.find(pair.first);
529 if (found == exit.fBefore.end()) {
530 // exit has no definition for it, just copy it
531 workList->insert(exitId);
ethannicholas22f939e2016-10-13 13:25:34 -0700532 exit.fBefore[pair.first] = e1;
533 } else {
Ethan Nicholas86a43402017-01-19 13:32:00 -0500534 // exit has a (possibly different) value already defined
535 std::unique_ptr<Expression>* e2 = exit.fBefore[pair.first];
ethannicholas22f939e2016-10-13 13:25:34 -0700536 if (e1 != e2) {
537 // definition has changed, merge and add exit block to worklist
538 workList->insert(exitId);
Ethan Nicholasaf197692017-02-27 13:26:45 -0500539 if (e1 && e2) {
540 exit.fBefore[pair.first] =
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400541 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression;
Ethan Nicholasaf197692017-02-27 13:26:45 -0500542 } else {
543 exit.fBefore[pair.first] = nullptr;
544 }
ethannicholas22f939e2016-10-13 13:25:34 -0700545 }
546 }
547 }
548 }
549}
550
551// returns a map which maps all local variables in the function to null, indicating that their value
552// is initially unknown
Ethan Nicholas86a43402017-01-19 13:32:00 -0500553static DefinitionMap compute_start_state(const CFG& cfg) {
554 DefinitionMap result;
Mike Klein6ad99092016-10-26 10:35:22 -0400555 for (const auto& block : cfg.fBlocks) {
556 for (const auto& node : block.fNodes) {
ethannicholas22f939e2016-10-13 13:25:34 -0700557 if (node.fKind == BasicBlock::Node::kStatement_Kind) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400558 SkASSERT(node.statement());
Ethan Nicholascb670962017-04-20 19:31:52 -0400559 const Statement* s = node.statement()->get();
Ethan Nicholase6592142020-09-08 10:22:09 -0400560 if (s->kind() == Statement::Kind::kVarDeclarations) {
John Stilesa5a97b42020-08-18 11:19:07 -0400561 const VarDeclarationsStatement* vd = &s->as<VarDeclarationsStatement>();
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000562 for (const auto& decl : vd->fDeclaration->fVars) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400563 if (decl->kind() == Statement::Kind::kVarDeclaration) {
John Stilesa5a97b42020-08-18 11:19:07 -0400564 result[decl->as<VarDeclaration>().fVar] = nullptr;
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000565 }
Mike Klein6ad99092016-10-26 10:35:22 -0400566 }
ethannicholas22f939e2016-10-13 13:25:34 -0700567 }
568 }
569 }
570 }
571 return result;
572}
573
Ethan Nicholascb670962017-04-20 19:31:52 -0400574/**
575 * Returns true if assigning to this lvalue has no effect.
576 */
577static bool is_dead(const Expression& lvalue) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400578 switch (lvalue.kind()) {
579 case Expression::Kind::kVariableReference:
John Stilesa5a97b42020-08-18 11:19:07 -0400580 return lvalue.as<VariableReference>().fVariable.dead();
Ethan Nicholase6592142020-09-08 10:22:09 -0400581 case Expression::Kind::kSwizzle:
John Stilesa5a97b42020-08-18 11:19:07 -0400582 return is_dead(*lvalue.as<Swizzle>().fBase);
Ethan Nicholase6592142020-09-08 10:22:09 -0400583 case Expression::Kind::kFieldAccess:
John Stilesa5a97b42020-08-18 11:19:07 -0400584 return is_dead(*lvalue.as<FieldAccess>().fBase);
Ethan Nicholase6592142020-09-08 10:22:09 -0400585 case Expression::Kind::kIndex: {
John Stilesa5a97b42020-08-18 11:19:07 -0400586 const IndexExpression& idx = lvalue.as<IndexExpression>();
Ethan Nicholas2a099da2020-01-02 14:40:54 -0500587 return is_dead(*idx.fBase) &&
588 !idx.fIndex->hasProperty(Expression::Property::kSideEffects);
Ethan Nicholascb670962017-04-20 19:31:52 -0400589 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400590 case Expression::Kind::kTernary: {
John Stilesa5a97b42020-08-18 11:19:07 -0400591 const TernaryExpression& t = lvalue.as<TernaryExpression>();
Ethan Nicholasa583b812018-01-18 13:32:11 -0500592 return !t.fTest->hasSideEffects() && is_dead(*t.fIfTrue) && is_dead(*t.fIfFalse);
593 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400594 case Expression::Kind::kExternalValue:
Ethan Nicholas91164d12019-05-15 15:29:54 -0400595 return false;
Ethan Nicholascb670962017-04-20 19:31:52 -0400596 default:
Ethan Nicholas2a099da2020-01-02 14:40:54 -0500597#ifdef SK_DEBUG
Ethan Nicholascb670962017-04-20 19:31:52 -0400598 ABORT("invalid lvalue: %s\n", lvalue.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -0500599#endif
600 return false;
Ethan Nicholascb670962017-04-20 19:31:52 -0400601 }
602}
ethannicholas22f939e2016-10-13 13:25:34 -0700603
Ethan Nicholascb670962017-04-20 19:31:52 -0400604/**
605 * Returns true if this is an assignment which can be collapsed down to just the right hand side due
606 * to a dead target and lack of side effects on the left hand side.
607 */
608static bool dead_assignment(const BinaryExpression& b) {
Ethan Nicholasbf66ffb2020-09-16 22:05:10 +0000609 if (!Compiler::IsAssignment(b.fOperator)) {
Ethan Nicholascb670962017-04-20 19:31:52 -0400610 return false;
611 }
Ethan Nicholasbf66ffb2020-09-16 22:05:10 +0000612 return is_dead(*b.fLeft);
Ethan Nicholascb670962017-04-20 19:31:52 -0400613}
614
615void Compiler::computeDataFlow(CFG* cfg) {
616 cfg->fBlocks[cfg->fStart].fBefore = compute_start_state(*cfg);
ethannicholas22f939e2016-10-13 13:25:34 -0700617 std::set<BlockId> workList;
Ethan Nicholascb670962017-04-20 19:31:52 -0400618 for (BlockId i = 0; i < cfg->fBlocks.size(); i++) {
ethannicholas22f939e2016-10-13 13:25:34 -0700619 workList.insert(i);
620 }
621 while (workList.size()) {
622 BlockId next = *workList.begin();
623 workList.erase(workList.begin());
Ethan Nicholascb670962017-04-20 19:31:52 -0400624 this->scanCFG(cfg, next, &workList);
ethannicholas22f939e2016-10-13 13:25:34 -0700625 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400626}
627
628/**
629 * Attempts to replace the expression pointed to by iter with a new one (in both the CFG and the
630 * IR). If the expression can be cleanly removed, returns true and updates the iterator to point to
631 * the newly-inserted element. Otherwise updates only the IR and returns false (and the CFG will
632 * need to be regenerated).
633 */
John Stilesafbf8992020-08-18 10:08:21 -0400634static bool try_replace_expression(BasicBlock* b,
635 std::vector<BasicBlock::Node>::iterator* iter,
636 std::unique_ptr<Expression>* newExpression) {
Ethan Nicholascb670962017-04-20 19:31:52 -0400637 std::unique_ptr<Expression>* target = (*iter)->expression();
638 if (!b->tryRemoveExpression(iter)) {
639 *target = std::move(*newExpression);
640 return false;
641 }
642 *target = std::move(*newExpression);
643 return b->tryInsertExpression(iter, target);
644}
645
646/**
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400647 * Returns true if the expression is a constant numeric literal with the specified value, or a
648 * constant vector with all elements equal to the specified value.
Ethan Nicholascb670962017-04-20 19:31:52 -0400649 */
John Stiles9d944232020-08-19 09:56:49 -0400650template <typename T = double>
651static bool is_constant(const Expression& expr, T value) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400652 switch (expr.kind()) {
653 case Expression::Kind::kIntLiteral:
John Stiles81365af2020-08-18 09:24:00 -0400654 return expr.as<IntLiteral>().fValue == value;
John Stiles9d944232020-08-19 09:56:49 -0400655
Ethan Nicholase6592142020-09-08 10:22:09 -0400656 case Expression::Kind::kFloatLiteral:
John Stiles81365af2020-08-18 09:24:00 -0400657 return expr.as<FloatLiteral>().fValue == value;
John Stiles9d944232020-08-19 09:56:49 -0400658
Ethan Nicholase6592142020-09-08 10:22:09 -0400659 case Expression::Kind::kConstructor: {
John Stiles9d944232020-08-19 09:56:49 -0400660 const Constructor& constructor = expr.as<Constructor>();
661 if (constructor.isCompileTimeConstant()) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400662 const Type& constructorType = constructor.type();
663 bool isFloat = constructorType.columns() > 1
664 ? constructorType.componentType().isFloat()
665 : constructorType.isFloat();
666 switch (constructorType.typeKind()) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400667 case Type::TypeKind::kVector:
Ethan Nicholas30d30222020-09-11 12:27:26 -0400668 for (int i = 0; i < constructorType.columns(); ++i) {
John Stiles9d944232020-08-19 09:56:49 -0400669 if (isFloat) {
670 if (constructor.getFVecComponent(i) != value) {
671 return false;
672 }
673 } else {
674 if (constructor.getIVecComponent(i) != value) {
675 return false;
676 }
677 }
Ethan Nicholasd188c182019-06-10 15:55:38 -0400678 }
John Stiles9d944232020-08-19 09:56:49 -0400679 return true;
680
Ethan Nicholase6592142020-09-08 10:22:09 -0400681 case Type::TypeKind::kScalar:
John Stiles9d944232020-08-19 09:56:49 -0400682 SkASSERT(constructor.fArguments.size() == 1);
683 return is_constant<T>(*constructor.fArguments[0], value);
684
685 default:
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400686 return false;
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400687 }
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400688 }
689 return false;
690 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400691 default:
692 return false;
693 }
694}
695
696/**
697 * Collapses the binary expression pointed to by iter down to just the right side (in both the IR
698 * and CFG structures).
699 */
John Stilesafbf8992020-08-18 10:08:21 -0400700static void delete_left(BasicBlock* b,
701 std::vector<BasicBlock::Node>::iterator* iter,
702 bool* outUpdated,
703 bool* outNeedsRescan) {
Ethan Nicholascb670962017-04-20 19:31:52 -0400704 *outUpdated = true;
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400705 std::unique_ptr<Expression>* target = (*iter)->expression();
John Stilesa5a97b42020-08-18 11:19:07 -0400706 BinaryExpression& bin = (*target)->as<BinaryExpression>();
Ethan Nicholasbf66ffb2020-09-16 22:05:10 +0000707 SkASSERT(!bin.fLeft->hasSideEffects());
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400708 bool result;
Ethan Nicholasbf66ffb2020-09-16 22:05:10 +0000709 if (bin.fOperator == Token::Kind::TK_EQ) {
710 result = b->tryRemoveLValueBefore(iter, bin.fLeft.get());
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400711 } else {
Ethan Nicholasbf66ffb2020-09-16 22:05:10 +0000712 result = b->tryRemoveExpressionBefore(iter, bin.fLeft.get());
Ethan Nicholascb670962017-04-20 19:31:52 -0400713 }
Ethan Nicholasbf66ffb2020-09-16 22:05:10 +0000714 *target = std::move(bin.fRight);
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400715 if (!result) {
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400716 *outNeedsRescan = true;
717 return;
718 }
719 if (*iter == b->fNodes.begin()) {
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400720 *outNeedsRescan = true;
721 return;
722 }
723 --(*iter);
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400724 if ((*iter)->fKind != BasicBlock::Node::kExpression_Kind ||
Ethan Nicholasbf66ffb2020-09-16 22:05:10 +0000725 (*iter)->expression() != &bin.fRight) {
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400726 *outNeedsRescan = true;
727 return;
728 }
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400729 *iter = b->fNodes.erase(*iter);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400730 SkASSERT((*iter)->expression() == target);
Ethan Nicholascb670962017-04-20 19:31:52 -0400731}
732
733/**
734 * Collapses the binary expression pointed to by iter down to just the left side (in both the IR and
735 * CFG structures).
736 */
John Stilesafbf8992020-08-18 10:08:21 -0400737static void delete_right(BasicBlock* b,
738 std::vector<BasicBlock::Node>::iterator* iter,
739 bool* outUpdated,
740 bool* outNeedsRescan) {
Ethan Nicholascb670962017-04-20 19:31:52 -0400741 *outUpdated = true;
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400742 std::unique_ptr<Expression>* target = (*iter)->expression();
John Stilesa5a97b42020-08-18 11:19:07 -0400743 BinaryExpression& bin = (*target)->as<BinaryExpression>();
Ethan Nicholasbf66ffb2020-09-16 22:05:10 +0000744 SkASSERT(!bin.fRight->hasSideEffects());
745 if (!b->tryRemoveExpressionBefore(iter, bin.fRight.get())) {
746 *target = std::move(bin.fLeft);
Ethan Nicholascb670962017-04-20 19:31:52 -0400747 *outNeedsRescan = true;
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400748 return;
Ethan Nicholascb670962017-04-20 19:31:52 -0400749 }
Ethan Nicholasbf66ffb2020-09-16 22:05:10 +0000750 *target = std::move(bin.fLeft);
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400751 if (*iter == b->fNodes.begin()) {
752 *outNeedsRescan = true;
753 return;
754 }
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400755 --(*iter);
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400756 if (((*iter)->fKind != BasicBlock::Node::kExpression_Kind ||
Ethan Nicholasbf66ffb2020-09-16 22:05:10 +0000757 (*iter)->expression() != &bin.fLeft)) {
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400758 *outNeedsRescan = true;
759 return;
760 }
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400761 *iter = b->fNodes.erase(*iter);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400762 SkASSERT((*iter)->expression() == target);
Ethan Nicholascb670962017-04-20 19:31:52 -0400763}
764
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400765/**
766 * Constructs the specified type using a single argument.
767 */
Ethan Nicholas30d30222020-09-11 12:27:26 -0400768static std::unique_ptr<Expression> construct(const Type* type, std::unique_ptr<Expression> v) {
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400769 std::vector<std::unique_ptr<Expression>> args;
770 args.push_back(std::move(v));
Ethan Nicholase6592142020-09-08 10:22:09 -0400771 std::unique_ptr<Expression> result = std::make_unique<Constructor>(-1, type, std::move(args));
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400772 return result;
773}
774
775/**
776 * Used in the implementations of vectorize_left and vectorize_right. Given a vector type and an
777 * expression x, deletes the expression pointed to by iter and replaces it with <type>(x).
778 */
779static void vectorize(BasicBlock* b,
780 std::vector<BasicBlock::Node>::iterator* iter,
781 const Type& type,
782 std::unique_ptr<Expression>* otherExpression,
783 bool* outUpdated,
784 bool* outNeedsRescan) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400785 SkASSERT((*(*iter)->expression())->kind() == Expression::Kind::kBinary);
786 SkASSERT(type.typeKind() == Type::TypeKind::kVector);
Ethan Nicholas30d30222020-09-11 12:27:26 -0400787 SkASSERT((*otherExpression)->type().typeKind() == Type::TypeKind::kScalar);
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400788 *outUpdated = true;
789 std::unique_ptr<Expression>* target = (*iter)->expression();
790 if (!b->tryRemoveExpression(iter)) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400791 *target = construct(&type, std::move(*otherExpression));
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400792 *outNeedsRescan = true;
793 } else {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400794 *target = construct(&type, std::move(*otherExpression));
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400795 if (!b->tryInsertExpression(iter, target)) {
796 *outNeedsRescan = true;
797 }
798 }
799}
800
801/**
802 * Given a binary expression of the form x <op> vec<n>(y), deletes the right side and vectorizes the
803 * left to yield vec<n>(x).
804 */
805static void vectorize_left(BasicBlock* b,
806 std::vector<BasicBlock::Node>::iterator* iter,
807 bool* outUpdated,
808 bool* outNeedsRescan) {
John Stilesa5a97b42020-08-18 11:19:07 -0400809 BinaryExpression& bin = (*(*iter)->expression())->as<BinaryExpression>();
Ethan Nicholasbf66ffb2020-09-16 22:05:10 +0000810 vectorize(b, iter, bin.fRight->type(), &bin.fLeft, outUpdated, outNeedsRescan);
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400811}
812
813/**
814 * Given a binary expression of the form vec<n>(x) <op> y, deletes the left side and vectorizes the
815 * right to yield vec<n>(y).
816 */
817static void vectorize_right(BasicBlock* b,
818 std::vector<BasicBlock::Node>::iterator* iter,
819 bool* outUpdated,
820 bool* outNeedsRescan) {
John Stilesa5a97b42020-08-18 11:19:07 -0400821 BinaryExpression& bin = (*(*iter)->expression())->as<BinaryExpression>();
Ethan Nicholasbf66ffb2020-09-16 22:05:10 +0000822 vectorize(b, iter, bin.fLeft->type(), &bin.fRight, outUpdated, outNeedsRescan);
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400823}
824
825// Mark that an expression which we were writing to is no longer being written to
John Stilesa5a97b42020-08-18 11:19:07 -0400826static void clear_write(Expression& expr) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400827 switch (expr.kind()) {
828 case Expression::Kind::kVariableReference: {
John Stilesa5a97b42020-08-18 11:19:07 -0400829 expr.as<VariableReference>().setRefKind(VariableReference::kRead_RefKind);
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400830 break;
831 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400832 case Expression::Kind::kFieldAccess:
John Stilesa5a97b42020-08-18 11:19:07 -0400833 clear_write(*expr.as<FieldAccess>().fBase);
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400834 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400835 case Expression::Kind::kSwizzle:
John Stilesa5a97b42020-08-18 11:19:07 -0400836 clear_write(*expr.as<Swizzle>().fBase);
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400837 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400838 case Expression::Kind::kIndex:
John Stilesa5a97b42020-08-18 11:19:07 -0400839 clear_write(*expr.as<IndexExpression>().fBase);
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400840 break;
841 default:
842 ABORT("shouldn't be writing to this kind of expression\n");
843 break;
844 }
845}
846
Ethan Nicholascb670962017-04-20 19:31:52 -0400847void Compiler::simplifyExpression(DefinitionMap& definitions,
848 BasicBlock& b,
849 std::vector<BasicBlock::Node>::iterator* iter,
850 std::unordered_set<const Variable*>* undefinedVariables,
851 bool* outUpdated,
852 bool* outNeedsRescan) {
853 Expression* expr = (*iter)->expression()->get();
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400854 SkASSERT(expr);
Ethan Nicholascb670962017-04-20 19:31:52 -0400855 if ((*iter)->fConstantPropagation) {
856 std::unique_ptr<Expression> optimized = expr->constantPropagate(*fIRGenerator, definitions);
857 if (optimized) {
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400858 *outUpdated = true;
Ethan Nicholas30d30222020-09-11 12:27:26 -0400859 optimized = fIRGenerator->coerce(std::move(optimized), expr->type());
Ethan Nicholas1d881522020-09-11 09:32:54 -0400860 SkASSERT(optimized);
Ethan Nicholascb670962017-04-20 19:31:52 -0400861 if (!try_replace_expression(&b, iter, &optimized)) {
862 *outNeedsRescan = true;
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400863 return;
Ethan Nicholascb670962017-04-20 19:31:52 -0400864 }
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400865 SkASSERT((*iter)->fKind == BasicBlock::Node::kExpression_Kind);
Ethan Nicholascb670962017-04-20 19:31:52 -0400866 expr = (*iter)->expression()->get();
Ethan Nicholascb670962017-04-20 19:31:52 -0400867 }
868 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400869 switch (expr->kind()) {
870 case Expression::Kind::kVariableReference: {
John Stilesa5a97b42020-08-18 11:19:07 -0400871 const VariableReference& ref = expr->as<VariableReference>();
Ethan Nicholas8f7e28f2018-03-26 14:24:27 -0400872 const Variable& var = ref.fVariable;
873 if (ref.refKind() != VariableReference::kWrite_RefKind &&
874 ref.refKind() != VariableReference::kPointer_RefKind &&
875 var.fStorage == Variable::kLocal_Storage && !definitions[&var] &&
Ethan Nicholascb670962017-04-20 19:31:52 -0400876 (*undefinedVariables).find(&var) == (*undefinedVariables).end()) {
877 (*undefinedVariables).insert(&var);
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000878 this->error(expr->fOffset,
879 "'" + var.fName + "' has not been assigned");
Ethan Nicholascb670962017-04-20 19:31:52 -0400880 }
881 break;
882 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400883 case Expression::Kind::kTernary: {
John Stiles403a3632020-08-20 12:11:48 -0400884 TernaryExpression* t = &expr->as<TernaryExpression>();
Ethan Nicholase6592142020-09-08 10:22:09 -0400885 if (t->fTest->kind() == Expression::Kind::kBoolLiteral) {
Ethan Nicholascb670962017-04-20 19:31:52 -0400886 // ternary has a constant test, replace it with either the true or
887 // false branch
John Stiles403a3632020-08-20 12:11:48 -0400888 if (t->fTest->as<BoolLiteral>().fValue) {
Ethan Nicholascb670962017-04-20 19:31:52 -0400889 (*iter)->setExpression(std::move(t->fIfTrue));
890 } else {
891 (*iter)->setExpression(std::move(t->fIfFalse));
892 }
893 *outUpdated = true;
894 *outNeedsRescan = true;
895 }
896 break;
897 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400898 case Expression::Kind::kBinary: {
John Stiles403a3632020-08-20 12:11:48 -0400899 BinaryExpression* bin = &expr->as<BinaryExpression>();
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400900 if (dead_assignment(*bin)) {
901 delete_left(&b, iter, outUpdated, outNeedsRescan);
902 break;
903 }
Ethan Nicholasbf66ffb2020-09-16 22:05:10 +0000904 const Type& leftType = bin->fLeft->type();
905 const Type& rightType = bin->fRight->type();
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400906 // collapse useless expressions like x * 1 or x + 0
Ethan Nicholas30d30222020-09-11 12:27:26 -0400907 if (((leftType.typeKind() != Type::TypeKind::kScalar) &&
908 (leftType.typeKind() != Type::TypeKind::kVector)) ||
909 ((rightType.typeKind() != Type::TypeKind::kScalar) &&
910 (rightType.typeKind() != Type::TypeKind::kVector))) {
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400911 break;
912 }
Ethan Nicholasbf66ffb2020-09-16 22:05:10 +0000913 switch (bin->fOperator) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400914 case Token::Kind::TK_STAR:
Ethan Nicholasbf66ffb2020-09-16 22:05:10 +0000915 if (is_constant(*bin->fLeft, 1)) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400916 if (leftType.typeKind() == Type::TypeKind::kVector &&
917 rightType.typeKind() == Type::TypeKind::kScalar) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400918 // float4(1) * x -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400919 vectorize_right(&b, iter, outUpdated, outNeedsRescan);
920 } else {
921 // 1 * x -> x
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400922 // 1 * float4(x) -> float4(x)
923 // float4(1) * float4(x) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400924 delete_left(&b, iter, outUpdated, outNeedsRescan);
925 }
926 }
Ethan Nicholasbf66ffb2020-09-16 22:05:10 +0000927 else if (is_constant(*bin->fLeft, 0)) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400928 if (leftType.typeKind() == Type::TypeKind::kScalar &&
929 rightType.typeKind() == Type::TypeKind::kVector &&
Ethan Nicholasbf66ffb2020-09-16 22:05:10 +0000930 !bin->fRight->hasSideEffects()) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400931 // 0 * float4(x) -> float4(0)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400932 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
933 } else {
934 // 0 * x -> 0
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400935 // float4(0) * x -> float4(0)
936 // float4(0) * float4(x) -> float4(0)
Ethan Nicholasbf66ffb2020-09-16 22:05:10 +0000937 if (!bin->fRight->hasSideEffects()) {
Ethan Nicholas51493ee2017-12-11 12:34:33 -0500938 delete_right(&b, iter, outUpdated, outNeedsRescan);
939 }
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400940 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400941 }
Ethan Nicholasbf66ffb2020-09-16 22:05:10 +0000942 else if (is_constant(*bin->fRight, 1)) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400943 if (leftType.typeKind() == Type::TypeKind::kScalar &&
944 rightType.typeKind() == Type::TypeKind::kVector) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400945 // x * float4(1) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400946 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
947 } else {
948 // x * 1 -> x
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400949 // float4(x) * 1 -> float4(x)
950 // float4(x) * float4(1) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400951 delete_right(&b, iter, outUpdated, outNeedsRescan);
952 }
953 }
Ethan Nicholasbf66ffb2020-09-16 22:05:10 +0000954 else if (is_constant(*bin->fRight, 0)) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400955 if (leftType.typeKind() == Type::TypeKind::kVector &&
956 rightType.typeKind() == Type::TypeKind::kScalar &&
Ethan Nicholasbf66ffb2020-09-16 22:05:10 +0000957 !bin->fLeft->hasSideEffects()) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400958 // float4(x) * 0 -> float4(0)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400959 vectorize_right(&b, iter, outUpdated, outNeedsRescan);
960 } else {
961 // x * 0 -> 0
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400962 // x * float4(0) -> float4(0)
963 // float4(x) * float4(0) -> float4(0)
Ethan Nicholasbf66ffb2020-09-16 22:05:10 +0000964 if (!bin->fLeft->hasSideEffects()) {
Ethan Nicholas51493ee2017-12-11 12:34:33 -0500965 delete_left(&b, iter, outUpdated, outNeedsRescan);
966 }
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400967 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400968 }
969 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400970 case Token::Kind::TK_PLUS:
Ethan Nicholasbf66ffb2020-09-16 22:05:10 +0000971 if (is_constant(*bin->fLeft, 0)) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400972 if (leftType.typeKind() == Type::TypeKind::kVector &&
973 rightType.typeKind() == Type::TypeKind::kScalar) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400974 // float4(0) + x -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400975 vectorize_right(&b, iter, outUpdated, outNeedsRescan);
976 } else {
977 // 0 + x -> x
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400978 // 0 + float4(x) -> float4(x)
979 // float4(0) + float4(x) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400980 delete_left(&b, iter, outUpdated, outNeedsRescan);
981 }
Ethan Nicholasbf66ffb2020-09-16 22:05:10 +0000982 } else if (is_constant(*bin->fRight, 0)) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400983 if (leftType.typeKind() == Type::TypeKind::kScalar &&
984 rightType.typeKind() == Type::TypeKind::kVector) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400985 // x + float4(0) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400986 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
987 } else {
988 // x + 0 -> x
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400989 // float4(x) + 0 -> float4(x)
990 // float4(x) + float4(0) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400991 delete_right(&b, iter, outUpdated, outNeedsRescan);
992 }
Ethan Nicholas56e42712017-04-21 10:23:37 -0400993 }
994 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400995 case Token::Kind::TK_MINUS:
Ethan Nicholasbf66ffb2020-09-16 22:05:10 +0000996 if (is_constant(*bin->fRight, 0)) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400997 if (leftType.typeKind() == Type::TypeKind::kScalar &&
998 rightType.typeKind() == Type::TypeKind::kVector) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400999 // x - float4(0) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -04001000 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
1001 } else {
1002 // x - 0 -> x
Ethan Nicholas5af9ea32017-07-28 15:19:46 -04001003 // float4(x) - 0 -> float4(x)
1004 // float4(x) - float4(0) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -04001005 delete_right(&b, iter, outUpdated, outNeedsRescan);
1006 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001007 }
1008 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001009 case Token::Kind::TK_SLASH:
Ethan Nicholasbf66ffb2020-09-16 22:05:10 +00001010 if (is_constant(*bin->fRight, 1)) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04001011 if (leftType.typeKind() == Type::TypeKind::kScalar &&
1012 rightType.typeKind() == Type::TypeKind::kVector) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -04001013 // x / float4(1) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -04001014 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
1015 } else {
1016 // x / 1 -> x
Ethan Nicholas5af9ea32017-07-28 15:19:46 -04001017 // float4(x) / 1 -> float4(x)
1018 // float4(x) / float4(1) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -04001019 delete_right(&b, iter, outUpdated, outNeedsRescan);
1020 }
Ethan Nicholasbf66ffb2020-09-16 22:05:10 +00001021 } else if (is_constant(*bin->fLeft, 0)) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04001022 if (leftType.typeKind() == Type::TypeKind::kScalar &&
1023 rightType.typeKind() == Type::TypeKind::kVector &&
Ethan Nicholasbf66ffb2020-09-16 22:05:10 +00001024 !bin->fRight->hasSideEffects()) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -04001025 // 0 / float4(x) -> float4(0)
Ethan Nicholasfe53e582017-04-27 16:24:51 -04001026 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
1027 } else {
1028 // 0 / x -> 0
Ethan Nicholas5af9ea32017-07-28 15:19:46 -04001029 // float4(0) / x -> float4(0)
1030 // float4(0) / float4(x) -> float4(0)
Ethan Nicholasbf66ffb2020-09-16 22:05:10 +00001031 if (!bin->fRight->hasSideEffects()) {
Ethan Nicholas51493ee2017-12-11 12:34:33 -05001032 delete_right(&b, iter, outUpdated, outNeedsRescan);
1033 }
Ethan Nicholasfe53e582017-04-27 16:24:51 -04001034 }
1035 }
1036 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001037 case Token::Kind::TK_PLUSEQ:
Ethan Nicholasbf66ffb2020-09-16 22:05:10 +00001038 if (is_constant(*bin->fRight, 0)) {
1039 clear_write(*bin->fLeft);
Ethan Nicholasfe53e582017-04-27 16:24:51 -04001040 delete_right(&b, iter, outUpdated, outNeedsRescan);
1041 }
1042 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001043 case Token::Kind::TK_MINUSEQ:
Ethan Nicholasbf66ffb2020-09-16 22:05:10 +00001044 if (is_constant(*bin->fRight, 0)) {
1045 clear_write(*bin->fLeft);
Ethan Nicholasfe53e582017-04-27 16:24:51 -04001046 delete_right(&b, iter, outUpdated, outNeedsRescan);
1047 }
1048 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001049 case Token::Kind::TK_STAREQ:
Ethan Nicholasbf66ffb2020-09-16 22:05:10 +00001050 if (is_constant(*bin->fRight, 1)) {
1051 clear_write(*bin->fLeft);
Ethan Nicholasfe53e582017-04-27 16:24:51 -04001052 delete_right(&b, iter, outUpdated, outNeedsRescan);
1053 }
1054 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001055 case Token::Kind::TK_SLASHEQ:
Ethan Nicholasbf66ffb2020-09-16 22:05:10 +00001056 if (is_constant(*bin->fRight, 1)) {
1057 clear_write(*bin->fLeft);
Ethan Nicholascb670962017-04-20 19:31:52 -04001058 delete_right(&b, iter, outUpdated, outNeedsRescan);
1059 }
1060 break;
1061 default:
1062 break;
1063 }
Ethan Nicholas409f6f02019-09-17 12:34:39 -04001064 break;
1065 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001066 case Expression::Kind::kSwizzle: {
John Stiles403a3632020-08-20 12:11:48 -04001067 Swizzle& s = expr->as<Swizzle>();
Ethan Nicholas409f6f02019-09-17 12:34:39 -04001068 // detect identity swizzles like foo.rgba
Ethan Nicholas30d30222020-09-11 12:27:26 -04001069 if ((int) s.fComponents.size() == s.fBase->type().columns()) {
Ethan Nicholas409f6f02019-09-17 12:34:39 -04001070 bool identity = true;
1071 for (int i = 0; i < (int) s.fComponents.size(); ++i) {
1072 if (s.fComponents[i] != i) {
1073 identity = false;
1074 break;
1075 }
1076 }
1077 if (identity) {
1078 *outUpdated = true;
1079 if (!try_replace_expression(&b, iter, &s.fBase)) {
1080 *outNeedsRescan = true;
1081 return;
1082 }
1083 SkASSERT((*iter)->fKind == BasicBlock::Node::kExpression_Kind);
1084 break;
1085 }
1086 }
1087 // detect swizzles of swizzles, e.g. replace foo.argb.r000 with foo.a000
Ethan Nicholase6592142020-09-08 10:22:09 -04001088 if (s.fBase->kind() == Expression::Kind::kSwizzle) {
John Stilesa5a97b42020-08-18 11:19:07 -04001089 Swizzle& base = s.fBase->as<Swizzle>();
Ethan Nicholas409f6f02019-09-17 12:34:39 -04001090 std::vector<int> final;
1091 for (int c : s.fComponents) {
Brian Osman25647672020-09-15 15:16:56 -04001092 final.push_back(base.fComponents[c]);
Ethan Nicholas409f6f02019-09-17 12:34:39 -04001093 }
1094 *outUpdated = true;
1095 std::unique_ptr<Expression> replacement(new Swizzle(*fContext, base.fBase->clone(),
1096 std::move(final)));
1097 if (!try_replace_expression(&b, iter, &replacement)) {
1098 *outNeedsRescan = true;
1099 return;
1100 }
1101 SkASSERT((*iter)->fKind == BasicBlock::Node::kExpression_Kind);
Ethan Nicholas409f6f02019-09-17 12:34:39 -04001102 }
John Stiles30212b72020-06-11 17:55:07 -04001103 break;
Ethan Nicholascb670962017-04-20 19:31:52 -04001104 }
1105 default:
1106 break;
1107 }
1108}
1109
John Stiles92219b42020-06-15 12:32:24 -04001110// Returns true if this statement could potentially execute a break at the current level. We ignore
1111// nested loops and switches, since any breaks inside of them will merely break the loop / switch.
John Stilesb92641c2020-08-31 18:09:01 -04001112static bool contains_conditional_break(Statement& stmt) {
1113 class ContainsConditionalBreak : public ProgramVisitor {
1114 public:
1115 bool visitStatement(const Statement& stmt) override {
Ethan Nicholase6592142020-09-08 10:22:09 -04001116 switch (stmt.kind()) {
1117 case Statement::Kind::kBlock:
John Stilesb92641c2020-08-31 18:09:01 -04001118 return this->INHERITED::visitStatement(stmt);
1119
Ethan Nicholase6592142020-09-08 10:22:09 -04001120 case Statement::Kind::kBreak:
John Stilesb92641c2020-08-31 18:09:01 -04001121 return fInConditional > 0;
1122
Ethan Nicholase6592142020-09-08 10:22:09 -04001123 case Statement::Kind::kIf: {
John Stilesb92641c2020-08-31 18:09:01 -04001124 ++fInConditional;
1125 bool result = this->INHERITED::visitStatement(stmt);
1126 --fInConditional;
1127 return result;
1128 }
1129
1130 default:
1131 return false;
1132 }
1133 }
1134
1135 int fInConditional = 0;
1136 using INHERITED = ProgramVisitor;
1137 };
1138
1139 return ContainsConditionalBreak{}.visitStatement(stmt);
John Stiles92219b42020-06-15 12:32:24 -04001140}
1141
Ethan Nicholas5005a222018-08-24 13:06:27 -04001142// returns true if this statement definitely executes a break at the current level (we ignore
1143// nested loops and switches, since any breaks inside of them will merely break the loop / switch)
John Stilesb92641c2020-08-31 18:09:01 -04001144static bool contains_unconditional_break(Statement& stmt) {
1145 class ContainsUnconditionalBreak : public ProgramVisitor {
1146 public:
1147 bool visitStatement(const Statement& stmt) override {
Ethan Nicholase6592142020-09-08 10:22:09 -04001148 switch (stmt.kind()) {
1149 case Statement::Kind::kBlock:
John Stilesb92641c2020-08-31 18:09:01 -04001150 return this->INHERITED::visitStatement(stmt);
1151
Ethan Nicholase6592142020-09-08 10:22:09 -04001152 case Statement::Kind::kBreak:
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001153 return true;
John Stilesb92641c2020-08-31 18:09:01 -04001154
1155 default:
1156 return false;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001157 }
John Stilesb92641c2020-08-31 18:09:01 -04001158 }
John Stiles92219b42020-06-15 12:32:24 -04001159
John Stilesb92641c2020-08-31 18:09:01 -04001160 using INHERITED = ProgramVisitor;
1161 };
John Stiles92219b42020-06-15 12:32:24 -04001162
John Stilesb92641c2020-08-31 18:09:01 -04001163 return ContainsUnconditionalBreak{}.visitStatement(stmt);
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001164}
1165
John Stiles92219b42020-06-15 12:32:24 -04001166static void move_all_but_break(std::unique_ptr<Statement>& stmt,
1167 std::vector<std::unique_ptr<Statement>>* target) {
Ethan Nicholase6592142020-09-08 10:22:09 -04001168 switch (stmt->kind()) {
1169 case Statement::Kind::kBlock: {
John Stiles92219b42020-06-15 12:32:24 -04001170 // Recurse into the block.
1171 Block& block = static_cast<Block&>(*stmt);
1172
1173 std::vector<std::unique_ptr<Statement>> blockStmts;
1174 blockStmts.reserve(block.fStatements.size());
1175 for (std::unique_ptr<Statement>& statementInBlock : block.fStatements) {
1176 move_all_but_break(statementInBlock, &blockStmts);
Ethan Nicholas739e1ca2020-06-11 12:16:14 -04001177 }
John Stiles92219b42020-06-15 12:32:24 -04001178
1179 target->push_back(std::make_unique<Block>(block.fOffset, std::move(blockStmts),
1180 block.fSymbols, block.fIsScope));
Ethan Nicholas739e1ca2020-06-11 12:16:14 -04001181 break;
John Stiles92219b42020-06-15 12:32:24 -04001182 }
1183
Ethan Nicholase6592142020-09-08 10:22:09 -04001184 case Statement::Kind::kBreak:
John Stiles92219b42020-06-15 12:32:24 -04001185 // Do not append a break to the target.
1186 break;
1187
Ethan Nicholas739e1ca2020-06-11 12:16:14 -04001188 default:
John Stiles92219b42020-06-15 12:32:24 -04001189 // Append normal statements to the target.
1190 target->push_back(std::move(stmt));
1191 break;
Ethan Nicholas739e1ca2020-06-11 12:16:14 -04001192 }
1193}
1194
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001195// Returns a block containing all of the statements that will be run if the given case matches
1196// (which, owing to the statements being owned by unique_ptrs, means the switch itself will be
1197// broken by this call and must then be discarded).
1198// Returns null (and leaves the switch unmodified) if no such simple reduction is possible, such as
1199// when break statements appear inside conditionals.
John Stiles92219b42020-06-15 12:32:24 -04001200static std::unique_ptr<Statement> block_for_case(SwitchStatement* switchStatement,
1201 SwitchCase* caseToCapture) {
1202 // We have to be careful to not move any of the pointers until after we're sure we're going to
1203 // succeed, so before we make any changes at all, we check the switch-cases to decide on a plan
1204 // of action. First, find the switch-case we are interested in.
1205 auto iter = switchStatement->fCases.begin();
1206 for (; iter != switchStatement->fCases.end(); ++iter) {
1207 if (iter->get() == caseToCapture) {
1208 break;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001209 }
John Stiles92219b42020-06-15 12:32:24 -04001210 }
1211
1212 // Next, walk forward through the rest of the switch. If we find a conditional break, we're
1213 // stuck and can't simplify at all. If we find an unconditional break, we have a range of
1214 // statements that we can use for simplification.
1215 auto startIter = iter;
1216 Statement* unconditionalBreakStmt = nullptr;
1217 for (; iter != switchStatement->fCases.end(); ++iter) {
1218 for (std::unique_ptr<Statement>& stmt : (*iter)->fStatements) {
1219 if (contains_conditional_break(*stmt)) {
1220 // We can't reduce switch-cases to a block when they have conditional breaks.
1221 return nullptr;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001222 }
John Stiles92219b42020-06-15 12:32:24 -04001223
1224 if (contains_unconditional_break(*stmt)) {
1225 // We found an unconditional break. We can use this block, but we need to strip
1226 // out the break statement.
1227 unconditionalBreakStmt = stmt.get();
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001228 break;
1229 }
1230 }
John Stiles92219b42020-06-15 12:32:24 -04001231
1232 if (unconditionalBreakStmt != nullptr) {
1233 break;
1234 }
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001235 }
John Stiles92219b42020-06-15 12:32:24 -04001236
1237 // We fell off the bottom of the switch or encountered a break. We know the range of statements
1238 // that we need to move over, and we know it's safe to do so.
1239 std::vector<std::unique_ptr<Statement>> caseStmts;
1240
1241 // We can move over most of the statements as-is.
1242 while (startIter != iter) {
1243 for (std::unique_ptr<Statement>& stmt : (*startIter)->fStatements) {
1244 caseStmts.push_back(std::move(stmt));
1245 }
1246 ++startIter;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001247 }
John Stiles92219b42020-06-15 12:32:24 -04001248
1249 // If we found an unconditional break at the end, we need to move what we can while avoiding
1250 // that break.
1251 if (unconditionalBreakStmt != nullptr) {
1252 for (std::unique_ptr<Statement>& stmt : (*startIter)->fStatements) {
1253 if (stmt.get() == unconditionalBreakStmt) {
1254 move_all_but_break(stmt, &caseStmts);
1255 unconditionalBreakStmt = nullptr;
1256 break;
1257 }
1258
1259 caseStmts.push_back(std::move(stmt));
1260 }
1261 }
1262
1263 SkASSERT(unconditionalBreakStmt == nullptr); // Verify that we fixed the unconditional break.
1264
1265 // Return our newly-synthesized block.
1266 return std::make_unique<Block>(/*offset=*/-1, std::move(caseStmts), switchStatement->fSymbols);
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001267}
1268
Ethan Nicholascb670962017-04-20 19:31:52 -04001269void Compiler::simplifyStatement(DefinitionMap& definitions,
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001270 BasicBlock& b,
1271 std::vector<BasicBlock::Node>::iterator* iter,
1272 std::unordered_set<const Variable*>* undefinedVariables,
1273 bool* outUpdated,
1274 bool* outNeedsRescan) {
Ethan Nicholascb670962017-04-20 19:31:52 -04001275 Statement* stmt = (*iter)->statement()->get();
Ethan Nicholase6592142020-09-08 10:22:09 -04001276 switch (stmt->kind()) {
1277 case Statement::Kind::kVarDeclaration: {
John Stilesa5a97b42020-08-18 11:19:07 -04001278 const auto& varDecl = stmt->as<VarDeclaration>();
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001279 if (varDecl.fVar->dead() &&
1280 (!varDecl.fValue ||
1281 !varDecl.fValue->hasSideEffects())) {
1282 if (varDecl.fValue) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001283 SkASSERT((*iter)->statement()->get() == stmt);
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001284 if (!b.tryRemoveExpressionBefore(iter, varDecl.fValue.get())) {
1285 *outNeedsRescan = true;
Ethan Nicholascb670962017-04-20 19:31:52 -04001286 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001287 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001288 (*iter)->setStatement(std::unique_ptr<Statement>(new Nop()));
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001289 *outUpdated = true;
Ethan Nicholascb670962017-04-20 19:31:52 -04001290 }
1291 break;
1292 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001293 case Statement::Kind::kIf: {
John Stilesa5a97b42020-08-18 11:19:07 -04001294 IfStatement& i = stmt->as<IfStatement>();
Ethan Nicholase6592142020-09-08 10:22:09 -04001295 if (i.fTest->kind() == Expression::Kind::kBoolLiteral) {
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001296 // constant if, collapse down to a single branch
John Stilesa5a97b42020-08-18 11:19:07 -04001297 if (i.fTest->as<BoolLiteral>().fValue) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001298 SkASSERT(i.fIfTrue);
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001299 (*iter)->setStatement(std::move(i.fIfTrue));
1300 } else {
1301 if (i.fIfFalse) {
1302 (*iter)->setStatement(std::move(i.fIfFalse));
1303 } else {
1304 (*iter)->setStatement(std::unique_ptr<Statement>(new Nop()));
1305 }
1306 }
1307 *outUpdated = true;
1308 *outNeedsRescan = true;
1309 break;
1310 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001311 if (i.fIfFalse && i.fIfFalse->isEmpty()) {
1312 // else block doesn't do anything, remove it
1313 i.fIfFalse.reset();
1314 *outUpdated = true;
1315 *outNeedsRescan = true;
1316 }
1317 if (!i.fIfFalse && i.fIfTrue->isEmpty()) {
1318 // if block doesn't do anything, no else block
1319 if (i.fTest->hasSideEffects()) {
1320 // test has side effects, keep it
1321 (*iter)->setStatement(std::unique_ptr<Statement>(
1322 new ExpressionStatement(std::move(i.fTest))));
1323 } else {
1324 // no if, no else, no test side effects, kill the whole if
1325 // statement
1326 (*iter)->setStatement(std::unique_ptr<Statement>(new Nop()));
1327 }
1328 *outUpdated = true;
1329 *outNeedsRescan = true;
1330 }
1331 break;
1332 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001333 case Statement::Kind::kSwitch: {
John Stilesa5a97b42020-08-18 11:19:07 -04001334 SwitchStatement& s = stmt->as<SwitchStatement>();
Ethan Nicholas34b19c52020-09-14 11:33:47 -04001335 int64_t switchValue;
1336 if (fIRGenerator->getConstantInt(*s.fValue, &switchValue)) {
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001337 // switch is constant, replace it with the case that matches
1338 bool found = false;
1339 SwitchCase* defaultCase = nullptr;
John Stiles9d944232020-08-19 09:56:49 -04001340 for (const std::unique_ptr<SwitchCase>& c : s.fCases) {
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001341 if (!c->fValue) {
1342 defaultCase = c.get();
1343 continue;
1344 }
Ethan Nicholas34b19c52020-09-14 11:33:47 -04001345 int64_t caseValue;
1346 SkAssertResult(fIRGenerator->getConstantInt(*c->fValue, &caseValue));
1347 if (caseValue == switchValue) {
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001348 std::unique_ptr<Statement> newBlock = block_for_case(&s, c.get());
1349 if (newBlock) {
1350 (*iter)->setStatement(std::move(newBlock));
John Stiles9d944232020-08-19 09:56:49 -04001351 found = true;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001352 break;
1353 } else {
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -04001354 if (s.fIsStatic && !(fFlags & kPermitInvalidStaticTests_Flag)) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001355 this->error(s.fOffset,
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001356 "static switch contains non-static conditional break");
1357 s.fIsStatic = false;
1358 }
1359 return; // can't simplify
1360 }
1361 }
1362 }
1363 if (!found) {
1364 // no matching case. use default if it exists, or kill the whole thing
1365 if (defaultCase) {
1366 std::unique_ptr<Statement> newBlock = block_for_case(&s, defaultCase);
1367 if (newBlock) {
1368 (*iter)->setStatement(std::move(newBlock));
1369 } else {
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -04001370 if (s.fIsStatic && !(fFlags & kPermitInvalidStaticTests_Flag)) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001371 this->error(s.fOffset,
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001372 "static switch contains non-static conditional break");
1373 s.fIsStatic = false;
1374 }
1375 return; // can't simplify
1376 }
1377 } else {
1378 (*iter)->setStatement(std::unique_ptr<Statement>(new Nop()));
1379 }
1380 }
1381 *outUpdated = true;
1382 *outNeedsRescan = true;
1383 }
1384 break;
1385 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001386 case Statement::Kind::kExpression: {
John Stilesa5a97b42020-08-18 11:19:07 -04001387 ExpressionStatement& e = stmt->as<ExpressionStatement>();
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001388 SkASSERT((*iter)->statement()->get() == &e);
Ethan Nicholascb670962017-04-20 19:31:52 -04001389 if (!e.fExpression->hasSideEffects()) {
1390 // Expression statement with no side effects, kill it
1391 if (!b.tryRemoveExpressionBefore(iter, e.fExpression.get())) {
1392 *outNeedsRescan = true;
1393 }
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001394 SkASSERT((*iter)->statement()->get() == stmt);
Ethan Nicholascb670962017-04-20 19:31:52 -04001395 (*iter)->setStatement(std::unique_ptr<Statement>(new Nop()));
1396 *outUpdated = true;
1397 }
1398 break;
1399 }
1400 default:
1401 break;
1402 }
1403}
1404
John Stiles0cc193a2020-09-09 09:39:34 -04001405bool Compiler::scanCFG(FunctionDefinition& f) {
1406 bool madeChanges = false;
1407
Ethan Nicholascb670962017-04-20 19:31:52 -04001408 CFG cfg = CFGGenerator().getCFG(f);
1409 this->computeDataFlow(&cfg);
ethannicholas22f939e2016-10-13 13:25:34 -07001410
1411 // check for unreachable code
1412 for (size_t i = 0; i < cfg.fBlocks.size(); i++) {
John Stiles0cc193a2020-09-09 09:39:34 -04001413 const BasicBlock& block = cfg.fBlocks[i];
1414 if (i != cfg.fStart && !block.fEntrances.size() && block.fNodes.size()) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001415 int offset;
John Stiles0cc193a2020-09-09 09:39:34 -04001416 const BasicBlock::Node& node = block.fNodes[0];
1417 switch (node.fKind) {
Ethan Nicholas86a43402017-01-19 13:32:00 -05001418 case BasicBlock::Node::kStatement_Kind:
John Stiles0cc193a2020-09-09 09:39:34 -04001419 offset = (*node.statement())->fOffset;
Ethan Nicholas86a43402017-01-19 13:32:00 -05001420 break;
1421 case BasicBlock::Node::kExpression_Kind:
John Stiles0cc193a2020-09-09 09:39:34 -04001422 offset = (*node.expression())->fOffset;
1423 if ((*node.expression())->is<BoolLiteral>()) {
Ethan Nicholas70728ef2020-05-28 07:09:00 -04001424 // Function inlining can generate do { ... } while(false) loops which always
1425 // break, so the boolean condition is considered unreachable. Since not
1426 // being able to reach a literal is a non-issue in the first place, we
1427 // don't report an error in this case.
1428 continue;
1429 }
Ethan Nicholas86a43402017-01-19 13:32:00 -05001430 break;
1431 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001432 this->error(offset, String("unreachable"));
ethannicholas22f939e2016-10-13 13:25:34 -07001433 }
1434 }
1435 if (fErrorCount) {
John Stiles0cc193a2020-09-09 09:39:34 -04001436 return madeChanges;
ethannicholas22f939e2016-10-13 13:25:34 -07001437 }
1438
Ethan Nicholascb670962017-04-20 19:31:52 -04001439 // check for dead code & undefined variables, perform constant propagation
1440 std::unordered_set<const Variable*> undefinedVariables;
1441 bool updated;
1442 bool needsRescan = false;
1443 do {
1444 if (needsRescan) {
1445 cfg = CFGGenerator().getCFG(f);
1446 this->computeDataFlow(&cfg);
1447 needsRescan = false;
Ethan Nicholas113628d2017-02-02 16:11:39 -05001448 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001449
1450 updated = false;
Ethan Nicholas1de14812020-06-19 15:32:49 -04001451 bool first = true;
Ethan Nicholascb670962017-04-20 19:31:52 -04001452 for (BasicBlock& b : cfg.fBlocks) {
Ethan Nicholas1de14812020-06-19 15:32:49 -04001453 if (!first && b.fEntrances.empty()) {
1454 // Block was reachable before optimization, but has since become unreachable. In
1455 // addition to being dead code, it's broken - since control flow can't reach it, no
1456 // prior variable definitions can reach it, and therefore variables might look to
1457 // have not been properly assigned. Kill it.
Brian Osmandb16c482020-09-09 15:15:06 -04001458
1459 // We need to do this in two steps. For any variable declarations, the node list
1460 // will contain statement nodes for each VarDeclaration, and then a statement for
1461 // the VarDeclarationsStatement. When we replace the VDS with a Nop, we delete the
1462 // storage of the unique_ptr that the VD nodes are pointing to. So we remove those
1463 // from the node list entirely, first.
1464 b.fNodes.erase(
1465 std::remove_if(b.fNodes.begin(), b.fNodes.end(),
1466 [](const BasicBlock::Node& node) {
1467 return node.fKind == BasicBlock::Node::kStatement_Kind &&
1468 (*node.statement())->is<VarDeclaration>();
1469 }),
1470 b.fNodes.end());
1471
1472 // Now replace any remaining statements in the block with Nops.
Ethan Nicholas1de14812020-06-19 15:32:49 -04001473 for (BasicBlock::Node& node : b.fNodes) {
1474 if (node.fKind == BasicBlock::Node::kStatement_Kind &&
John Stiles0cc193a2020-09-09 09:39:34 -04001475 !(*node.statement())->is<Nop>()) {
1476 node.setStatement(std::make_unique<Nop>());
1477 madeChanges = true;
Ethan Nicholas1de14812020-06-19 15:32:49 -04001478 }
1479 }
1480 continue;
1481 }
1482 first = false;
Ethan Nicholascb670962017-04-20 19:31:52 -04001483 DefinitionMap definitions = b.fBefore;
1484
1485 for (auto iter = b.fNodes.begin(); iter != b.fNodes.end() && !needsRescan; ++iter) {
1486 if (iter->fKind == BasicBlock::Node::kExpression_Kind) {
1487 this->simplifyExpression(definitions, b, &iter, &undefinedVariables, &updated,
1488 &needsRescan);
1489 } else {
1490 this->simplifyStatement(definitions, b, &iter, &undefinedVariables, &updated,
John Stiles0cc193a2020-09-09 09:39:34 -04001491 &needsRescan);
Ethan Nicholascb670962017-04-20 19:31:52 -04001492 }
Ethan Nicholas4b330df2017-05-17 10:52:55 -04001493 if (needsRescan) {
1494 break;
1495 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001496 this->addDefinitions(*iter, &definitions);
1497 }
Brian Osman01a3eb42020-09-14 11:32:49 -04001498
1499 if (needsRescan) {
1500 break;
1501 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001502 }
John Stiles0cc193a2020-09-09 09:39:34 -04001503 madeChanges |= updated;
Ethan Nicholascb670962017-04-20 19:31:52 -04001504 } while (updated);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001505 SkASSERT(!needsRescan);
ethannicholas22f939e2016-10-13 13:25:34 -07001506
Ethan Nicholas91a10532017-06-22 11:24:38 -04001507 // verify static ifs & switches, clean up dead variable decls
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001508 for (BasicBlock& b : cfg.fBlocks) {
1509 DefinitionMap definitions = b.fBefore;
1510
Ethan Nicholas91a10532017-06-22 11:24:38 -04001511 for (auto iter = b.fNodes.begin(); iter != b.fNodes.end() && !needsRescan;) {
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001512 if (iter->fKind == BasicBlock::Node::kStatement_Kind) {
1513 const Statement& s = **iter->statement();
Ethan Nicholase6592142020-09-08 10:22:09 -04001514 switch (s.kind()) {
1515 case Statement::Kind::kIf:
John Stilesa5a97b42020-08-18 11:19:07 -04001516 if (s.as<IfStatement>().fIsStatic &&
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -04001517 !(fFlags & kPermitInvalidStaticTests_Flag)) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001518 this->error(s.fOffset, "static if has non-static test");
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001519 }
Ethan Nicholas91a10532017-06-22 11:24:38 -04001520 ++iter;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001521 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001522 case Statement::Kind::kSwitch:
John Stilesa5a97b42020-08-18 11:19:07 -04001523 if (s.as<SwitchStatement>().fIsStatic &&
John Stiles0cc193a2020-09-09 09:39:34 -04001524 !(fFlags & kPermitInvalidStaticTests_Flag)) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001525 this->error(s.fOffset, "static switch has non-static test");
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001526 }
Ethan Nicholas91a10532017-06-22 11:24:38 -04001527 ++iter;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001528 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001529 case Statement::Kind::kVarDeclarations: {
John Stilesa5a97b42020-08-18 11:19:07 -04001530 VarDeclarations& decls = *s.as<VarDeclarationsStatement>().fDeclaration;
John Stiles0cc193a2020-09-09 09:39:34 -04001531 decls.fVars.erase(
1532 std::remove_if(decls.fVars.begin(), decls.fVars.end(),
1533 [&](const std::unique_ptr<Statement>& var) {
1534 bool nop = var->is<Nop>();
1535 madeChanges |= nop;
1536 return nop;
1537 }),
1538 decls.fVars.end());
1539 if (decls.fVars.empty()) {
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001540 iter = b.fNodes.erase(iter);
1541 } else {
1542 ++iter;
1543 }
1544 break;
1545 }
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001546 default:
Ethan Nicholas91a10532017-06-22 11:24:38 -04001547 ++iter;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001548 break;
1549 }
Ethan Nicholas91a10532017-06-22 11:24:38 -04001550 } else {
1551 ++iter;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001552 }
1553 }
1554 }
1555
ethannicholas22f939e2016-10-13 13:25:34 -07001556 // check for missing return
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001557 if (f.fDeclaration.fReturnType != *fContext->fVoid_Type) {
ethannicholas22f939e2016-10-13 13:25:34 -07001558 if (cfg.fBlocks[cfg.fExit].fEntrances.size()) {
Ethan Nicholasdb80f692019-11-22 14:06:12 -05001559 this->error(f.fOffset, String("function '" + String(f.fDeclaration.fName) +
1560 "' can exit without returning a value"));
ethannicholas22f939e2016-10-13 13:25:34 -07001561 }
1562 }
John Stiles0cc193a2020-09-09 09:39:34 -04001563
1564 return madeChanges;
ethannicholas22f939e2016-10-13 13:25:34 -07001565}
1566
Ethan Nicholas91164d12019-05-15 15:29:54 -04001567void Compiler::registerExternalValue(ExternalValue* value) {
1568 fIRGenerator->fRootSymbolTable->addWithoutOwnership(value->fName, value);
1569}
1570
Ethan Nicholasc18bb512020-07-28 14:46:53 -04001571const Symbol* Compiler::takeOwnership(std::unique_ptr<const Symbol> symbol) {
John Stiles3ae071e2020-08-05 15:29:29 -04001572 return fIRGenerator->fRootSymbolTable->takeOwnershipOfSymbol(std::move(symbol));
Ethan Nicholas91164d12019-05-15 15:29:54 -04001573}
1574
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001575std::unique_ptr<Program> Compiler::convertProgram(Program::Kind kind, String text,
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001576 const Program::Settings& settings) {
ethannicholasb3058bd2016-07-01 08:22:01 -07001577 fErrorText = "";
1578 fErrorCount = 0;
John Stiles7b463002020-08-31 17:29:21 -04001579 fInliner.reset(context(), settings);
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001580 std::vector<std::unique_ptr<ProgramElement>>* inherited;
ethannicholasd598f792016-07-25 10:08:54 -07001581 std::vector<std::unique_ptr<ProgramElement>> elements;
ethannicholasb3058bd2016-07-01 08:22:01 -07001582 switch (kind) {
1583 case Program::kVertex_Kind:
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001584 inherited = &fVertexInclude;
1585 fIRGenerator->fSymbolTable = fVertexSymbolTable;
John Stiles810c8cf2020-08-26 19:46:27 -04001586 fIRGenerator->fIntrinsics = fGPUIntrinsics.get();
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001587 fIRGenerator->start(&settings, inherited);
ethannicholasb3058bd2016-07-01 08:22:01 -07001588 break;
1589 case Program::kFragment_Kind:
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001590 inherited = &fFragmentInclude;
1591 fIRGenerator->fSymbolTable = fFragmentSymbolTable;
John Stiles810c8cf2020-08-26 19:46:27 -04001592 fIRGenerator->fIntrinsics = fGPUIntrinsics.get();
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001593 fIRGenerator->start(&settings, inherited);
ethannicholasb3058bd2016-07-01 08:22:01 -07001594 break;
Ethan Nicholas52cad152017-02-16 16:37:32 -05001595 case Program::kGeometry_Kind:
Ethan Nicholasc18bb512020-07-28 14:46:53 -04001596 this->loadGeometryIntrinsics();
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001597 inherited = &fGeometryInclude;
1598 fIRGenerator->fSymbolTable = fGeometrySymbolTable;
John Stiles810c8cf2020-08-26 19:46:27 -04001599 fIRGenerator->fIntrinsics = fGPUIntrinsics.get();
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001600 fIRGenerator->start(&settings, inherited);
Ethan Nicholas52cad152017-02-16 16:37:32 -05001601 break;
Ethan Nicholasb33fa3f2020-08-06 13:00:19 -04001602 case Program::kFragmentProcessor_Kind: {
Brian Osmandd496172020-08-08 08:17:18 -04001603#if !SKSL_STANDALONE
Ethan Nicholasc18bb512020-07-28 14:46:53 -04001604 {
1605 Rehydrator rehydrator(fContext.get(), fGpuSymbolTable, this,
1606 SKSL_INCLUDE_sksl_fp,
1607 SKSL_INCLUDE_sksl_fp_LENGTH);
1608 fFPSymbolTable = rehydrator.symbolTable();
1609 fFPInclude = rehydrator.elements();
1610 }
Brian Osman2b469eb2020-09-21 11:32:10 -04001611 fFPIntrinsics = std::make_unique<IRIntrinsicMap>(fGPUIntrinsics.get());
1612 grab_intrinsics(&fFPInclude, fFPIntrinsics.get());
1613
Ethan Nicholasc18bb512020-07-28 14:46:53 -04001614 inherited = &fFPInclude;
1615 fIRGenerator->fSymbolTable = fFPSymbolTable;
Brian Osman2b469eb2020-09-21 11:32:10 -04001616 fIRGenerator->fIntrinsics = fFPIntrinsics.get();
Ethan Nicholasc18bb512020-07-28 14:46:53 -04001617 fIRGenerator->start(&settings, inherited);
1618 break;
1619#else
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001620 inherited = nullptr;
Ethan Nicholas8da1e652019-05-24 11:01:59 -04001621 fIRGenerator->fSymbolTable = fGpuSymbolTable;
Ethan Nicholasb33fa3f2020-08-06 13:00:19 -04001622 fIRGenerator->start(&settings, /*inherited=*/nullptr, /*builtin=*/true);
John Stiles810c8cf2020-08-26 19:46:27 -04001623 fIRGenerator->fIntrinsics = fGPUIntrinsics.get();
Ethan Nicholasb33fa3f2020-08-06 13:00:19 -04001624 std::ifstream in(SKSL_FP_INCLUDE);
1625 std::string stdText{std::istreambuf_iterator<char>(in),
1626 std::istreambuf_iterator<char>()};
1627 if (in.rdstate()) {
1628 printf("error reading %s\n", SKSL_FP_INCLUDE);
1629 abort();
1630 }
1631 const String* source = fGpuSymbolTable->takeOwnershipOfString(
1632 std::make_unique<String>(stdText.c_str()));
1633 fIRGenerator->convertProgram(kind, source->c_str(), source->length(), &elements);
Ethan Nicholasc18bb512020-07-28 14:46:53 -04001634 fIRGenerator->fIsBuiltinCode = false;
Ethan Nicholas762466e2017-06-29 10:03:38 -04001635 break;
Ethan Nicholasc18bb512020-07-28 14:46:53 -04001636#endif
Ethan Nicholasb33fa3f2020-08-06 13:00:19 -04001637 }
Ethan Nicholas8da1e652019-05-24 11:01:59 -04001638 case Program::kPipelineStage_Kind:
Ethan Nicholasc18bb512020-07-28 14:46:53 -04001639 this->loadPipelineIntrinsics();
Ethan Nicholas8da1e652019-05-24 11:01:59 -04001640 inherited = &fPipelineInclude;
1641 fIRGenerator->fSymbolTable = fPipelineSymbolTable;
John Stiles810c8cf2020-08-26 19:46:27 -04001642 fIRGenerator->fIntrinsics = fGPUIntrinsics.get();
Ethan Nicholas8da1e652019-05-24 11:01:59 -04001643 fIRGenerator->start(&settings, inherited);
1644 break;
Ethan Nicholas746035a2019-04-23 13:31:09 -04001645 case Program::kGeneric_Kind:
Ethan Nicholasc18bb512020-07-28 14:46:53 -04001646 this->loadInterpreterIntrinsics();
Brian Osmaneac49832020-09-18 11:49:22 -04001647 inherited = nullptr;
Ethan Nicholas8da1e652019-05-24 11:01:59 -04001648 fIRGenerator->fSymbolTable = fInterpreterSymbolTable;
John Stiles810c8cf2020-08-26 19:46:27 -04001649 fIRGenerator->fIntrinsics = fInterpreterIntrinsics.get();
Brian Osmaneac49832020-09-18 11:49:22 -04001650 fIRGenerator->start(&settings, /*inherited=*/nullptr);
Ethan Nicholas0d997662019-04-08 09:46:01 -04001651 break;
ethannicholasb3058bd2016-07-01 08:22:01 -07001652 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001653 std::unique_ptr<String> textPtr(new String(std::move(text)));
1654 fSource = textPtr.get();
Ethan Nicholasc18bb512020-07-28 14:46:53 -04001655 fIRGenerator->convertProgram(kind, textPtr->c_str(), textPtr->size(), &elements);
John Stilesfbd050b2020-08-03 13:21:46 -04001656 auto result = std::make_unique<Program>(kind,
1657 std::move(textPtr),
1658 settings,
1659 fContext,
1660 inherited,
1661 std::move(elements),
1662 fIRGenerator->fSymbolTable,
1663 fIRGenerator->fInputs);
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001664 if (fErrorCount) {
1665 return nullptr;
1666 }
Ethan Nicholas34b19c52020-09-14 11:33:47 -04001667 if (settings.fOptimize && !this->optimize(*result)) {
1668 return nullptr;
1669 }
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001670 return result;
1671}
1672
Ethan Nicholas00543112018-07-31 09:44:36 -04001673bool Compiler::optimize(Program& program) {
1674 SkASSERT(!fErrorCount);
Ethan Nicholas34b19c52020-09-14 11:33:47 -04001675 fIRGenerator->fKind = program.fKind;
1676 fIRGenerator->fSettings = &program.fSettings;
John Stiles7954d6c2020-09-01 10:53:02 -04001677
Ethan Nicholas34b19c52020-09-14 11:33:47 -04001678 while (fErrorCount == 0) {
1679 bool madeChanges = false;
John Stiles7954d6c2020-09-01 10:53:02 -04001680
Ethan Nicholas34b19c52020-09-14 11:33:47 -04001681 // Scan and optimize based on the control-flow graph for each function.
1682 for (ProgramElement& element : program) {
1683 if (element.is<FunctionDefinition>()) {
1684 madeChanges |= this->scanCFG(element.as<FunctionDefinition>());
1685 }
1686 }
1687
1688 // Perform inline-candidate analysis and inline any functions deemed suitable.
John Stiles881a10c2020-09-19 10:13:24 -04001689 madeChanges |= fInliner.analyze(program);
Ethan Nicholas34b19c52020-09-14 11:33:47 -04001690
1691 // Remove dead functions. We wait until after analysis so that we still report errors,
1692 // even in unused code.
1693 if (program.fSettings.fRemoveDeadFunctions) {
1694 program.fElements.erase(
1695 std::remove_if(program.fElements.begin(),
1696 program.fElements.end(),
1697 [&](const std::unique_ptr<ProgramElement>& element) {
1698 if (!element->is<FunctionDefinition>()) {
1699 return false;
1700 }
1701 const auto& fn = element->as<FunctionDefinition>();
1702 bool dead = fn.fDeclaration.fCallCount == 0 &&
1703 fn.fDeclaration.fName != "main";
1704 madeChanges |= dead;
1705 return dead;
1706 }),
1707 program.fElements.end());
1708 }
1709
1710 if (program.fKind != Program::kFragmentProcessor_Kind) {
1711 // Remove dead variables.
John Stileseadfc3b2020-09-02 14:12:41 -04001712 for (ProgramElement& element : program) {
Ethan Nicholas34b19c52020-09-14 11:33:47 -04001713 if (!element.is<VarDeclarations>()) {
1714 continue;
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001715 }
Ethan Nicholas34b19c52020-09-14 11:33:47 -04001716 VarDeclarations& vars = element.as<VarDeclarations>();
1717 vars.fVars.erase(
1718 std::remove_if(vars.fVars.begin(), vars.fVars.end(),
1719 [&](const std::unique_ptr<Statement>& stmt) {
1720 bool dead = stmt->as<VarDeclaration>().fVar->dead();
John Stiles73a6bff2020-09-09 13:40:37 -04001721 madeChanges |= dead;
1722 return dead;
1723 }),
Ethan Nicholas34b19c52020-09-14 11:33:47 -04001724 vars.fVars.end());
John Stiles73a6bff2020-09-09 13:40:37 -04001725 }
1726
Ethan Nicholas34b19c52020-09-14 11:33:47 -04001727 // Remove empty variable declarations with no variables left inside of them.
1728 program.fElements.erase(
1729 std::remove_if(program.fElements.begin(), program.fElements.end(),
1730 [&](const std::unique_ptr<ProgramElement>& element) {
1731 if (!element->is<VarDeclarations>()) {
1732 return false;
1733 }
1734 bool dead = element->as<VarDeclarations>().fVars.empty();
1735 madeChanges |= dead;
1736 return dead;
1737 }),
1738 program.fElements.end());
1739 }
John Stiles73a6bff2020-09-09 13:40:37 -04001740
Ethan Nicholas34b19c52020-09-14 11:33:47 -04001741 if (!madeChanges) {
1742 break;
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001743 }
Ethan Nicholas00543112018-07-31 09:44:36 -04001744 }
1745 return fErrorCount == 0;
1746}
1747
Brian Osmanfb32ddf2019-06-18 10:14:20 -04001748#if defined(SKSL_STANDALONE) || SK_SUPPORT_GPU
1749
Ethan Nicholas00543112018-07-31 09:44:36 -04001750bool Compiler::toSPIRV(Program& program, OutputStream& out) {
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001751#ifdef SK_ENABLE_SPIRV_VALIDATION
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001752 StringStream buffer;
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001753 fSource = program.fSource.get();
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001754 SPIRVCodeGenerator cg(fContext.get(), &program, this, &buffer);
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001755 bool result = cg.generateCode();
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001756 fSource = nullptr;
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001757 if (result) {
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001758 spvtools::SpirvTools tools(SPV_ENV_VULKAN_1_0);
Ethan Nicholas762466e2017-06-29 10:03:38 -04001759 const String& data = buffer.str();
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001760 SkASSERT(0 == data.size() % 4);
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001761 auto dumpmsg = [](spv_message_level_t, const char*, const spv_position_t&, const char* m) {
1762 SkDebugf("SPIR-V validation error: %s\n", m);
1763 };
1764 tools.SetMessageConsumer(dumpmsg);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001765 // Verify that the SPIR-V we produced is valid. If this SkASSERT fails, check the logs prior
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001766 // to the failure to see the validation errors.
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001767 SkAssertResult(tools.Validate((const uint32_t*) data.c_str(), data.size() / 4));
Ethan Nicholas762466e2017-06-29 10:03:38 -04001768 out.write(data.c_str(), data.size());
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001769 }
1770#else
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001771 fSource = program.fSource.get();
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001772 SPIRVCodeGenerator cg(fContext.get(), &program, this, &out);
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001773 bool result = cg.generateCode();
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001774 fSource = nullptr;
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001775#endif
Ethan Nicholasce33f102016-12-09 17:22:59 -05001776 return result;
1777}
1778
Ethan Nicholas00543112018-07-31 09:44:36 -04001779bool Compiler::toSPIRV(Program& program, String* out) {
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001780 StringStream buffer;
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001781 bool result = this->toSPIRV(program, buffer);
1782 if (result) {
Ethan Nicholas762466e2017-06-29 10:03:38 -04001783 *out = buffer.str();
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001784 }
1785 return result;
1786}
1787
Ethan Nicholas00543112018-07-31 09:44:36 -04001788bool Compiler::toGLSL(Program& program, OutputStream& out) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001789 fSource = program.fSource.get();
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001790 GLSLCodeGenerator cg(fContext.get(), &program, this, &out);
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001791 bool result = cg.generateCode();
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001792 fSource = nullptr;
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001793 return result;
1794}
1795
Ethan Nicholas00543112018-07-31 09:44:36 -04001796bool Compiler::toGLSL(Program& program, String* out) {
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001797 StringStream buffer;
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001798 bool result = this->toGLSL(program, buffer);
1799 if (result) {
Ethan Nicholas762466e2017-06-29 10:03:38 -04001800 *out = buffer.str();
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001801 }
1802 return result;
1803}
1804
Brian Osmanc0243912020-02-19 15:35:26 -05001805bool Compiler::toHLSL(Program& program, String* out) {
1806 String spirv;
1807 if (!this->toSPIRV(program, &spirv)) {
1808 return false;
1809 }
1810
1811 return SPIRVtoHLSL(spirv, out);
1812}
1813
Ethan Nicholas00543112018-07-31 09:44:36 -04001814bool Compiler::toMetal(Program& program, OutputStream& out) {
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001815 MetalCodeGenerator cg(fContext.get(), &program, this, &out);
Ethan Nicholascc305772017-10-13 16:17:45 -04001816 bool result = cg.generateCode();
Ethan Nicholascc305772017-10-13 16:17:45 -04001817 return result;
1818}
1819
Ethan Nicholas00543112018-07-31 09:44:36 -04001820bool Compiler::toMetal(Program& program, String* out) {
Timothy Liangb8eeb802018-07-23 16:46:16 -04001821 StringStream buffer;
1822 bool result = this->toMetal(program, buffer);
1823 if (result) {
1824 *out = buffer.str();
1825 }
1826 return result;
1827}
1828
Ethan Nicholas2a479a52020-08-18 16:29:45 -04001829#if defined(SKSL_STANDALONE) || defined(GR_TEST_UTILS)
Ethan Nicholas00543112018-07-31 09:44:36 -04001830bool Compiler::toCPP(Program& program, String name, OutputStream& out) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001831 fSource = program.fSource.get();
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001832 CPPCodeGenerator cg(fContext.get(), &program, this, name, &out);
Ethan Nicholas762466e2017-06-29 10:03:38 -04001833 bool result = cg.generateCode();
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001834 fSource = nullptr;
Ethan Nicholas762466e2017-06-29 10:03:38 -04001835 return result;
1836}
1837
Ethan Nicholas00543112018-07-31 09:44:36 -04001838bool Compiler::toH(Program& program, String name, OutputStream& out) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001839 fSource = program.fSource.get();
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001840 HCodeGenerator cg(fContext.get(), &program, this, name, &out);
Ethan Nicholas762466e2017-06-29 10:03:38 -04001841 bool result = cg.generateCode();
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001842 fSource = nullptr;
Ethan Nicholas00543112018-07-31 09:44:36 -04001843 return result;
1844}
Ethan Nicholas2a479a52020-08-18 16:29:45 -04001845#endif // defined(SKSL_STANDALONE) || defined(GR_TEST_UTILS)
Ethan Nicholas00543112018-07-31 09:44:36 -04001846
Ethan Nicholas2a479a52020-08-18 16:29:45 -04001847#endif // defined(SKSL_STANDALONE) || SK_SUPPORT_GPU
Brian Osman2e29ab52019-09-20 12:19:11 -04001848
1849#if !defined(SKSL_STANDALONE) && SK_SUPPORT_GPU
Brian Osmana4b91692020-08-10 14:26:16 -04001850bool Compiler::toPipelineStage(Program& program, PipelineStageArgs* outArgs) {
Ethan Nicholas00543112018-07-31 09:44:36 -04001851 fSource = program.fSource.get();
1852 StringStream buffer;
Brian Osman300fe1d2020-01-23 15:42:43 -05001853 PipelineStageCodeGenerator cg(fContext.get(), &program, this, &buffer, outArgs);
Ethan Nicholas00543112018-07-31 09:44:36 -04001854 bool result = cg.generateCode();
1855 fSource = nullptr;
1856 if (result) {
Brian Osman107c6662019-12-30 15:02:30 -05001857 outArgs->fCode = buffer.str();
Ethan Nicholas00543112018-07-31 09:44:36 -04001858 }
Ethan Nicholas762466e2017-06-29 10:03:38 -04001859 return result;
1860}
Brian Osmanfb32ddf2019-06-18 10:14:20 -04001861#endif
1862
Ethan Nicholas0e9401d2019-03-21 11:05:37 -04001863std::unique_ptr<ByteCode> Compiler::toByteCode(Program& program) {
Mike Klein853d4ed2020-08-20 00:41:00 +00001864#if defined(SK_ENABLE_SKSL_INTERPRETER)
Brian Osman808f0212020-01-21 15:36:47 -05001865 fSource = program.fSource.get();
Ethan Nicholas0e9401d2019-03-21 11:05:37 -04001866 std::unique_ptr<ByteCode> result(new ByteCode());
Brian Osmanb08cc022020-04-02 11:38:40 -04001867 ByteCodeGenerator cg(fContext.get(), &program, this, result.get());
1868 bool success = cg.generateCode();
1869 fSource = nullptr;
1870 if (success) {
Ethan Nicholas0e9401d2019-03-21 11:05:37 -04001871 return result;
1872 }
Mike Klein853d4ed2020-08-20 00:41:00 +00001873#else
1874 ABORT("ByteCode interpreter not enabled");
1875#endif
Ethan Nicholas0e9401d2019-03-21 11:05:37 -04001876 return nullptr;
1877}
1878
Brian Osman401a0092020-09-10 14:47:24 -04001879const char* Compiler::OperatorName(Token::Kind op) {
1880 switch (op) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001881 case Token::Kind::TK_PLUS: return "+";
1882 case Token::Kind::TK_MINUS: return "-";
1883 case Token::Kind::TK_STAR: return "*";
1884 case Token::Kind::TK_SLASH: return "/";
1885 case Token::Kind::TK_PERCENT: return "%";
1886 case Token::Kind::TK_SHL: return "<<";
1887 case Token::Kind::TK_SHR: return ">>";
1888 case Token::Kind::TK_LOGICALNOT: return "!";
1889 case Token::Kind::TK_LOGICALAND: return "&&";
1890 case Token::Kind::TK_LOGICALOR: return "||";
1891 case Token::Kind::TK_LOGICALXOR: return "^^";
1892 case Token::Kind::TK_BITWISENOT: return "~";
1893 case Token::Kind::TK_BITWISEAND: return "&";
1894 case Token::Kind::TK_BITWISEOR: return "|";
1895 case Token::Kind::TK_BITWISEXOR: return "^";
1896 case Token::Kind::TK_EQ: return "=";
1897 case Token::Kind::TK_EQEQ: return "==";
1898 case Token::Kind::TK_NEQ: return "!=";
1899 case Token::Kind::TK_LT: return "<";
1900 case Token::Kind::TK_GT: return ">";
1901 case Token::Kind::TK_LTEQ: return "<=";
1902 case Token::Kind::TK_GTEQ: return ">=";
1903 case Token::Kind::TK_PLUSEQ: return "+=";
1904 case Token::Kind::TK_MINUSEQ: return "-=";
1905 case Token::Kind::TK_STAREQ: return "*=";
1906 case Token::Kind::TK_SLASHEQ: return "/=";
1907 case Token::Kind::TK_PERCENTEQ: return "%=";
1908 case Token::Kind::TK_SHLEQ: return "<<=";
1909 case Token::Kind::TK_SHREQ: return ">>=";
1910 case Token::Kind::TK_LOGICALANDEQ: return "&&=";
1911 case Token::Kind::TK_LOGICALOREQ: return "||=";
1912 case Token::Kind::TK_LOGICALXOREQ: return "^^=";
1913 case Token::Kind::TK_BITWISEANDEQ: return "&=";
1914 case Token::Kind::TK_BITWISEOREQ: return "|=";
1915 case Token::Kind::TK_BITWISEXOREQ: return "^=";
1916 case Token::Kind::TK_PLUSPLUS: return "++";
1917 case Token::Kind::TK_MINUSMINUS: return "--";
1918 case Token::Kind::TK_COMMA: return ",";
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001919 default:
Brian Osman401a0092020-09-10 14:47:24 -04001920 ABORT("unsupported operator: %d\n", (int) op);
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001921 }
1922}
1923
1924
1925bool Compiler::IsAssignment(Token::Kind op) {
1926 switch (op) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001927 case Token::Kind::TK_EQ: // fall through
1928 case Token::Kind::TK_PLUSEQ: // fall through
1929 case Token::Kind::TK_MINUSEQ: // fall through
1930 case Token::Kind::TK_STAREQ: // fall through
1931 case Token::Kind::TK_SLASHEQ: // fall through
1932 case Token::Kind::TK_PERCENTEQ: // fall through
1933 case Token::Kind::TK_SHLEQ: // fall through
1934 case Token::Kind::TK_SHREQ: // fall through
1935 case Token::Kind::TK_BITWISEOREQ: // fall through
1936 case Token::Kind::TK_BITWISEXOREQ: // fall through
1937 case Token::Kind::TK_BITWISEANDEQ: // fall through
1938 case Token::Kind::TK_LOGICALOREQ: // fall through
1939 case Token::Kind::TK_LOGICALXOREQ: // fall through
1940 case Token::Kind::TK_LOGICALANDEQ:
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001941 return true;
1942 default:
1943 return false;
1944 }
1945}
1946
Brian Osman401a0092020-09-10 14:47:24 -04001947Token::Kind Compiler::RemoveAssignment(Token::Kind op) {
1948 switch (op) {
1949 case Token::Kind::TK_PLUSEQ: return Token::Kind::TK_PLUS;
1950 case Token::Kind::TK_MINUSEQ: return Token::Kind::TK_MINUS;
1951 case Token::Kind::TK_STAREQ: return Token::Kind::TK_STAR;
1952 case Token::Kind::TK_SLASHEQ: return Token::Kind::TK_SLASH;
1953 case Token::Kind::TK_PERCENTEQ: return Token::Kind::TK_PERCENT;
1954 case Token::Kind::TK_SHLEQ: return Token::Kind::TK_SHL;
1955 case Token::Kind::TK_SHREQ: return Token::Kind::TK_SHR;
1956 case Token::Kind::TK_BITWISEOREQ: return Token::Kind::TK_BITWISEOR;
1957 case Token::Kind::TK_BITWISEXOREQ: return Token::Kind::TK_BITWISEXOR;
1958 case Token::Kind::TK_BITWISEANDEQ: return Token::Kind::TK_BITWISEAND;
1959 case Token::Kind::TK_LOGICALOREQ: return Token::Kind::TK_LOGICALOR;
1960 case Token::Kind::TK_LOGICALXOREQ: return Token::Kind::TK_LOGICALXOR;
1961 case Token::Kind::TK_LOGICALANDEQ: return Token::Kind::TK_LOGICALAND;
1962 default: return op;
1963 }
1964}
1965
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001966Position Compiler::position(int offset) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001967 SkASSERT(fSource);
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001968 int line = 1;
1969 int column = 1;
1970 for (int i = 0; i < offset; i++) {
1971 if ((*fSource)[i] == '\n') {
1972 ++line;
1973 column = 1;
1974 }
1975 else {
1976 ++column;
1977 }
1978 }
1979 return Position(line, column);
1980}
1981
1982void Compiler::error(int offset, String msg) {
ethannicholasb3058bd2016-07-01 08:22:01 -07001983 fErrorCount++;
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001984 Position pos = this->position(offset);
1985 fErrorText += "error: " + to_string(pos.fLine) + ": " + msg.c_str() + "\n";
ethannicholasb3058bd2016-07-01 08:22:01 -07001986}
1987
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001988String Compiler::errorText() {
Ethan Nicholas00543112018-07-31 09:44:36 -04001989 this->writeErrorCount();
1990 fErrorCount = 0;
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001991 String result = fErrorText;
ethannicholasb3058bd2016-07-01 08:22:01 -07001992 return result;
1993}
1994
1995void Compiler::writeErrorCount() {
1996 if (fErrorCount) {
1997 fErrorText += to_string(fErrorCount) + " error";
1998 if (fErrorCount > 1) {
1999 fErrorText += "s";
2000 }
2001 fErrorText += "\n";
2002 }
2003}
2004
John Stilesa6841be2020-08-06 14:11:56 -04002005} // namespace SkSL