blob: de6a241e1e9a2bff2317fc4a7f01b54031e5ce55 [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"
John Stilese6150002020-10-05 12:03:53 -040036#include "src/utils/SkBitSet.h"
ethannicholasb3058bd2016-07-01 08:22:01 -070037
Ethan Nicholasb33fa3f2020-08-06 13:00:19 -040038#include <fstream>
39
Ethan Nicholasa11035b2019-11-26 16:27:47 -050040#if !defined(SKSL_STANDALONE) & SK_SUPPORT_GPU
41#include "include/gpu/GrContextOptions.h"
42#include "src/gpu/GrShaderCaps.h"
43#endif
44
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -040045#ifdef SK_ENABLE_SPIRV_VALIDATION
46#include "spirv-tools/libspirv.hpp"
47#endif
48
Brian Osmandd496172020-08-08 08:17:18 -040049#if !SKSL_STANDALONE
Ethan Nicholasc18bb512020-07-28 14:46:53 -040050
51#include "src/sksl/generated/sksl_fp.dehydrated.sksl"
52#include "src/sksl/generated/sksl_frag.dehydrated.sksl"
53#include "src/sksl/generated/sksl_geom.dehydrated.sksl"
54#include "src/sksl/generated/sksl_gpu.dehydrated.sksl"
55#include "src/sksl/generated/sksl_interp.dehydrated.sksl"
56#include "src/sksl/generated/sksl_pipeline.dehydrated.sksl"
57#include "src/sksl/generated/sksl_vert.dehydrated.sksl"
58
59#else
60
Brian Osmandd496172020-08-08 08:17:18 -040061// GN generates or copies all of these files to the skslc executable directory
62static const char SKSL_GPU_INCLUDE[] = "sksl_gpu.sksl";
63static const char SKSL_INTERP_INCLUDE[] = "sksl_interp.sksl";
64static const char SKSL_VERT_INCLUDE[] = "sksl_vert.sksl";
65static const char SKSL_FRAG_INCLUDE[] = "sksl_frag.sksl";
66static const char SKSL_GEOM_INCLUDE[] = "sksl_geom.sksl";
67static const char SKSL_FP_INCLUDE[] = "sksl_fp.sksl";
68static const char SKSL_PIPELINE_INCLUDE[] = "sksl_pipeline.sksl";
Ethan Nicholasc18bb512020-07-28 14:46:53 -040069
70#endif
Ethan Nicholas0d997662019-04-08 09:46:01 -040071
ethannicholasb3058bd2016-07-01 08:22:01 -070072namespace SkSL {
73
Ethan Nicholasdb80f692019-11-22 14:06:12 -050074static void grab_intrinsics(std::vector<std::unique_ptr<ProgramElement>>* src,
John Stiles810c8cf2020-08-26 19:46:27 -040075 IRIntrinsicMap* target) {
Brian Osman08f986d2020-05-13 17:06:46 -040076 for (auto iter = src->begin(); iter != src->end(); ) {
77 std::unique_ptr<ProgramElement>& element = *iter;
Ethan Nicholase6592142020-09-08 10:22:09 -040078 switch (element->kind()) {
79 case ProgramElement::Kind::kFunction: {
John Stiles3dc0da62020-08-19 17:48:31 -040080 FunctionDefinition& f = element->as<FunctionDefinition>();
Brian Osman08f986d2020-05-13 17:06:46 -040081 SkASSERT(f.fDeclaration.fBuiltin);
Brian Osman2b469eb2020-09-21 11:32:10 -040082 target->insertOrDie(f.fDeclaration.description(), std::move(element));
Brian Osman08f986d2020-05-13 17:06:46 -040083 iter = src->erase(iter);
Ethan Nicholasdb80f692019-11-22 14:06:12 -050084 break;
85 }
Ethan Nicholase6592142020-09-08 10:22:09 -040086 case ProgramElement::Kind::kEnum: {
John Stiles3dc0da62020-08-19 17:48:31 -040087 Enum& e = element->as<Enum>();
Ethan Nicholasd83ded82020-09-29 17:05:54 -040088 target->insertOrDie(e.typeName(), std::move(element));
Brian Osman08f986d2020-05-13 17:06:46 -040089 iter = src->erase(iter);
Ethan Nicholasdb80f692019-11-22 14:06:12 -050090 break;
91 }
Brian Osmanc0213602020-10-06 14:43:32 -040092 case ProgramElement::Kind::kGlobalVar: {
93 const GlobalVarDeclaration& vd = element->as<GlobalVarDeclaration>();
94 const Variable* var = vd.fDecl->fVar;
Ethan Nicholase2c49992020-10-05 11:49:11 -040095 target->insertOrDie(var->name(), std::move(element));
Brian Osman8e2ef022020-09-30 13:26:43 -040096 iter = src->erase(iter);
97 break;
98 }
Ethan Nicholasdb80f692019-11-22 14:06:12 -050099 default:
Brian Osman00a8b5b2020-10-02 09:06:04 -0400100 printf("Unsupported element: %s\n", element->description().c_str());
101 SkASSERT(false);
Brian Osman2b469eb2020-09-21 11:32:10 -0400102 break;
Ethan Nicholasdb80f692019-11-22 14:06:12 -0500103 }
104 }
105}
106
John Stilesbc0c29e2020-09-28 13:13:40 -0400107static void reset_call_counts(std::vector<std::unique_ptr<ProgramElement>>* src) {
108 for (std::unique_ptr<ProgramElement>& element : *src) {
109 if (element->is<FunctionDefinition>()) {
110 const FunctionDeclaration& fnDecl = element->as<FunctionDefinition>().fDeclaration;
111 fnDecl.fCallCount = 0;
112 }
113 }
114}
115
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -0400116Compiler::Compiler(Flags flags)
Brian Osman00a8b5b2020-10-02 09:06:04 -0400117: fFlags(flags)
John Stiles810c8cf2020-08-26 19:46:27 -0400118, fContext(std::make_shared<Context>())
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -0400119, fErrorCount(0) {
Brian Osmaneac49832020-09-18 11:49:22 -0400120 fRootSymbolTable = std::make_shared<SymbolTable>(this);
John Stiles941fc712020-09-19 12:47:10 +0000121 fIRGenerator =
122 std::make_unique<IRGenerator>(fContext.get(), &fInliner, fRootSymbolTable, *this);
Ethan Nicholase2c49992020-10-05 11:49:11 -0400123 #define ADD_TYPE(t) fRootSymbolTable->addWithoutOwnership(fContext->f ## t ## _Type->name(), \
Brian Osmaneac49832020-09-18 11:49:22 -0400124 fContext->f ## t ## _Type.get())
ethannicholasb3058bd2016-07-01 08:22:01 -0700125 ADD_TYPE(Void);
126 ADD_TYPE(Float);
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400127 ADD_TYPE(Float2);
128 ADD_TYPE(Float3);
129 ADD_TYPE(Float4);
Ethan Nicholasdcba08e2017-08-02 10:52:54 -0400130 ADD_TYPE(Half);
131 ADD_TYPE(Half2);
132 ADD_TYPE(Half3);
133 ADD_TYPE(Half4);
ethannicholasb3058bd2016-07-01 08:22:01 -0700134 ADD_TYPE(Int);
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400135 ADD_TYPE(Int2);
136 ADD_TYPE(Int3);
137 ADD_TYPE(Int4);
ethannicholasb3058bd2016-07-01 08:22:01 -0700138 ADD_TYPE(UInt);
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400139 ADD_TYPE(UInt2);
140 ADD_TYPE(UInt3);
141 ADD_TYPE(UInt4);
Ethan Nicholasdcba08e2017-08-02 10:52:54 -0400142 ADD_TYPE(Short);
143 ADD_TYPE(Short2);
144 ADD_TYPE(Short3);
145 ADD_TYPE(Short4);
146 ADD_TYPE(UShort);
147 ADD_TYPE(UShort2);
148 ADD_TYPE(UShort3);
149 ADD_TYPE(UShort4);
Ruiqi Maob609e6d2018-07-17 10:19:38 -0400150 ADD_TYPE(Byte);
151 ADD_TYPE(Byte2);
152 ADD_TYPE(Byte3);
153 ADD_TYPE(Byte4);
154 ADD_TYPE(UByte);
155 ADD_TYPE(UByte2);
156 ADD_TYPE(UByte3);
157 ADD_TYPE(UByte4);
ethannicholasb3058bd2016-07-01 08:22:01 -0700158 ADD_TYPE(Bool);
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400159 ADD_TYPE(Bool2);
160 ADD_TYPE(Bool3);
161 ADD_TYPE(Bool4);
162 ADD_TYPE(Float2x2);
163 ADD_TYPE(Float2x3);
164 ADD_TYPE(Float2x4);
165 ADD_TYPE(Float3x2);
166 ADD_TYPE(Float3x3);
167 ADD_TYPE(Float3x4);
168 ADD_TYPE(Float4x2);
169 ADD_TYPE(Float4x3);
170 ADD_TYPE(Float4x4);
Ethan Nicholasdcba08e2017-08-02 10:52:54 -0400171 ADD_TYPE(Half2x2);
172 ADD_TYPE(Half2x3);
173 ADD_TYPE(Half2x4);
174 ADD_TYPE(Half3x2);
175 ADD_TYPE(Half3x3);
176 ADD_TYPE(Half3x4);
177 ADD_TYPE(Half4x2);
178 ADD_TYPE(Half4x3);
179 ADD_TYPE(Half4x4);
ethannicholasb3058bd2016-07-01 08:22:01 -0700180 ADD_TYPE(GenType);
Ethan Nicholasdcba08e2017-08-02 10:52:54 -0400181 ADD_TYPE(GenHType);
ethannicholasb3058bd2016-07-01 08:22:01 -0700182 ADD_TYPE(GenIType);
183 ADD_TYPE(GenUType);
184 ADD_TYPE(GenBType);
185 ADD_TYPE(Mat);
186 ADD_TYPE(Vec);
187 ADD_TYPE(GVec);
188 ADD_TYPE(GVec2);
189 ADD_TYPE(GVec3);
190 ADD_TYPE(GVec4);
Ethan Nicholasdcba08e2017-08-02 10:52:54 -0400191 ADD_TYPE(HVec);
ethannicholasb3058bd2016-07-01 08:22:01 -0700192 ADD_TYPE(IVec);
193 ADD_TYPE(UVec);
Ethan Nicholasdcba08e2017-08-02 10:52:54 -0400194 ADD_TYPE(SVec);
195 ADD_TYPE(USVec);
Ruiqi Maob609e6d2018-07-17 10:19:38 -0400196 ADD_TYPE(ByteVec);
197 ADD_TYPE(UByteVec);
ethannicholasb3058bd2016-07-01 08:22:01 -0700198 ADD_TYPE(BVec);
199
200 ADD_TYPE(Sampler1D);
201 ADD_TYPE(Sampler2D);
202 ADD_TYPE(Sampler3D);
ethannicholas5961bc92016-10-12 06:39:56 -0700203 ADD_TYPE(SamplerExternalOES);
ethannicholasb3058bd2016-07-01 08:22:01 -0700204 ADD_TYPE(SamplerCube);
205 ADD_TYPE(Sampler2DRect);
206 ADD_TYPE(Sampler1DArray);
207 ADD_TYPE(Sampler2DArray);
208 ADD_TYPE(SamplerCubeArray);
209 ADD_TYPE(SamplerBuffer);
210 ADD_TYPE(Sampler2DMS);
211 ADD_TYPE(Sampler2DMSArray);
212
Brian Salomonbf7b6202016-11-11 16:08:03 -0500213 ADD_TYPE(ISampler2D);
214
Brian Salomon2a51de82016-11-16 12:06:01 -0500215 ADD_TYPE(Image2D);
216 ADD_TYPE(IImage2D);
217
Greg Daniel64773e62016-11-22 09:44:03 -0500218 ADD_TYPE(SubpassInput);
219 ADD_TYPE(SubpassInputMS);
220
ethannicholasb3058bd2016-07-01 08:22:01 -0700221 ADD_TYPE(GSampler1D);
222 ADD_TYPE(GSampler2D);
223 ADD_TYPE(GSampler3D);
224 ADD_TYPE(GSamplerCube);
225 ADD_TYPE(GSampler2DRect);
226 ADD_TYPE(GSampler1DArray);
227 ADD_TYPE(GSampler2DArray);
228 ADD_TYPE(GSamplerCubeArray);
229 ADD_TYPE(GSamplerBuffer);
230 ADD_TYPE(GSampler2DMS);
231 ADD_TYPE(GSampler2DMSArray);
232
233 ADD_TYPE(Sampler1DShadow);
234 ADD_TYPE(Sampler2DShadow);
235 ADD_TYPE(SamplerCubeShadow);
236 ADD_TYPE(Sampler2DRectShadow);
237 ADD_TYPE(Sampler1DArrayShadow);
238 ADD_TYPE(Sampler2DArrayShadow);
239 ADD_TYPE(SamplerCubeArrayShadow);
240 ADD_TYPE(GSampler2DArrayShadow);
241 ADD_TYPE(GSamplerCubeArrayShadow);
Ethan Nicholasc9472af2017-10-10 16:30:21 -0400242 ADD_TYPE(FragmentProcessor);
Stephen Whiteff5d7a22019-07-26 17:42:06 -0400243 ADD_TYPE(Sampler);
244 ADD_TYPE(Texture2D);
ethannicholasb3058bd2016-07-01 08:22:01 -0700245
Brian Osman28590d52020-03-23 16:59:08 -0400246 StringFragment fpAliasName("shader");
John Stiles49a547f2020-10-06 16:14:37 -0400247 fRootSymbolTable->addAlias(fpAliasName, fContext->fFragmentProcessor_Type.get());
Brian Osman28590d52020-03-23 16:59:08 -0400248
Brian Osman3887a012020-09-30 13:22:27 -0400249 // sk_Caps is "builtin", but all references to it are resolved to Settings, so we don't need to
250 // treat it as builtin (ie, no need to clone it into the Program).
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700251 StringFragment skCapsName("sk_Caps");
Brian Osman3887a012020-09-30 13:22:27 -0400252 fRootSymbolTable->add(skCapsName,
Ethan Nicholas041fd0a2020-10-07 16:42:04 -0400253 std::make_unique<Variable>(/*offset=*/-1,
254 fIRGenerator->fModifiers->handle(Modifiers()),
255 skCapsName, fContext->fSkCaps_Type.get(),
Brian Osman3887a012020-09-30 13:22:27 -0400256 /*builtin=*/false, Variable::kGlobal_Storage));
Ethan Nicholas3605ace2016-11-21 15:59:48 -0500257
Brian Osman00a8b5b2020-10-02 09:06:04 -0400258 fIRGenerator->fIntrinsics = nullptr;
259 std::vector<std::unique_ptr<ProgramElement>> gpuElements;
260 std::vector<std::unique_ptr<ProgramElement>> fragElements;
Brian Osmandd496172020-08-08 08:17:18 -0400261#if SKSL_STANDALONE
Brian Osmaneac49832020-09-18 11:49:22 -0400262 this->processIncludeFile(Program::kFragment_Kind, SKSL_GPU_INCLUDE, fRootSymbolTable,
Brian Osman00a8b5b2020-10-02 09:06:04 -0400263 &gpuElements, &fGpuSymbolTable);
Ethan Nicholasb33fa3f2020-08-06 13:00:19 -0400264 this->processIncludeFile(Program::kVertex_Kind, SKSL_VERT_INCLUDE, fGpuSymbolTable,
265 &fVertexInclude, &fVertexSymbolTable);
266 this->processIncludeFile(Program::kFragment_Kind, SKSL_FRAG_INCLUDE, fGpuSymbolTable,
Brian Osman00a8b5b2020-10-02 09:06:04 -0400267 &fragElements, &fFragmentSymbolTable);
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400268#else
269 {
Ethan Nicholas041fd0a2020-10-07 16:42:04 -0400270 Rehydrator rehydrator(&fIRGenerator->fContext, fIRGenerator->fModifiers.get(),
271 fRootSymbolTable, this, SKSL_INCLUDE_sksl_gpu,
Brian Osmaneac49832020-09-18 11:49:22 -0400272 SKSL_INCLUDE_sksl_gpu_LENGTH);
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400273 fGpuSymbolTable = rehydrator.symbolTable();
Brian Osman00a8b5b2020-10-02 09:06:04 -0400274 gpuElements = rehydrator.elements();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -0400275 fModifiers.push_back(fIRGenerator->releaseModifiers());
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400276 }
277 {
Ethan Nicholas041fd0a2020-10-07 16:42:04 -0400278 Rehydrator rehydrator(&fIRGenerator->fContext, fIRGenerator->fModifiers.get(),
279 fGpuSymbolTable, this, SKSL_INCLUDE_sksl_vert,
Brian Osmaneac49832020-09-18 11:49:22 -0400280 SKSL_INCLUDE_sksl_vert_LENGTH);
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400281 fVertexSymbolTable = rehydrator.symbolTable();
282 fVertexInclude = rehydrator.elements();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -0400283 fModifiers.push_back(fIRGenerator->releaseModifiers());
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400284 }
285 {
Ethan Nicholas041fd0a2020-10-07 16:42:04 -0400286 Rehydrator rehydrator(&fIRGenerator->fContext, fIRGenerator->fModifiers.get(),
287 fGpuSymbolTable, this, SKSL_INCLUDE_sksl_frag,
Brian Osmaneac49832020-09-18 11:49:22 -0400288 SKSL_INCLUDE_sksl_frag_LENGTH);
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400289 fFragmentSymbolTable = rehydrator.symbolTable();
Brian Osman00a8b5b2020-10-02 09:06:04 -0400290 fragElements = rehydrator.elements();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -0400291 fModifiers.push_back(fIRGenerator->releaseModifiers());
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400292 }
293#endif
John Stilesbc0c29e2020-09-28 13:13:40 -0400294 // Call counts are used to track dead-stripping and inlinability within the program being
295 // currently compiled, and always should start at zero for a new program. Zero out any call
296 // counts that were registered during the assembly of the intrinsics/include data. (If we
297 // actually use calls from inside the intrinsics, we will clone them into the program and they
298 // will get new call counts.)
Brian Osman00a8b5b2020-10-02 09:06:04 -0400299 reset_call_counts(&gpuElements);
John Stilesbc0c29e2020-09-28 13:13:40 -0400300 reset_call_counts(&fVertexInclude);
Brian Osman00a8b5b2020-10-02 09:06:04 -0400301 reset_call_counts(&fragElements);
John Stilesbc0c29e2020-09-28 13:13:40 -0400302
Brian Osman00a8b5b2020-10-02 09:06:04 -0400303 fGPUIntrinsics = std::make_unique<IRIntrinsicMap>(/*parent=*/nullptr);
304 grab_intrinsics(&gpuElements, fGPUIntrinsics.get());
305
306 fFragmentIntrinsics = std::make_unique<IRIntrinsicMap>(fGPUIntrinsics.get());
307 grab_intrinsics(&fragElements, fFragmentIntrinsics.get());
ethannicholasb3058bd2016-07-01 08:22:01 -0700308}
309
John Stiles656427a2020-08-27 15:26:26 -0400310Compiler::~Compiler() {}
ethannicholasb3058bd2016-07-01 08:22:01 -0700311
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400312void Compiler::loadGeometryIntrinsics() {
313 if (fGeometrySymbolTable) {
314 return;
315 }
Brian Osmandd496172020-08-08 08:17:18 -0400316 #if !SKSL_STANDALONE
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400317 {
Ethan Nicholas041fd0a2020-10-07 16:42:04 -0400318 Rehydrator rehydrator(&fIRGenerator->fContext, fIRGenerator->fModifiers.get(),
319 fGpuSymbolTable, this, SKSL_INCLUDE_sksl_geom,
320 SKSL_INCLUDE_sksl_geom_LENGTH);
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400321 fGeometrySymbolTable = rehydrator.symbolTable();
322 fGeometryInclude = rehydrator.elements();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -0400323 fModifiers.push_back(fIRGenerator->releaseModifiers());
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400324 }
325 #else
Ethan Nicholasb33fa3f2020-08-06 13:00:19 -0400326 this->processIncludeFile(Program::kGeometry_Kind, SKSL_GEOM_INCLUDE, fGpuSymbolTable,
327 &fGeometryInclude, &fGeometrySymbolTable);
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400328 #endif
329}
330
Brian Osman8e2ef022020-09-30 13:26:43 -0400331void Compiler::loadFPIntrinsics() {
332 if (fFPSymbolTable) {
333 return;
334 }
335 fFPIntrinsics = std::make_unique<IRIntrinsicMap>(fGPUIntrinsics.get());
336 std::vector<std::unique_ptr<ProgramElement>> fpElements;
337 #if !SKSL_STANDALONE
338 {
Ethan Nicholas041fd0a2020-10-07 16:42:04 -0400339 Rehydrator rehydrator(&fIRGenerator->fContext, fIRGenerator->fModifiers.get(),
340 fGpuSymbolTable, this, SKSL_INCLUDE_sksl_fp,
Brian Osman8e2ef022020-09-30 13:26:43 -0400341 SKSL_INCLUDE_sksl_fp_LENGTH);
342 fFPSymbolTable = rehydrator.symbolTable();
343 fpElements = rehydrator.elements();
344 }
345 #else
346 this->processIncludeFile(Program::kFragmentProcessor_Kind, SKSL_FP_INCLUDE, fGpuSymbolTable,
347 &fpElements, &fFPSymbolTable);
348 #endif
349 grab_intrinsics(&fpElements, fFPIntrinsics.get());
Brian Osman8e2ef022020-09-30 13:26:43 -0400350}
351
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400352void Compiler::loadPipelineIntrinsics() {
353 if (fPipelineSymbolTable) {
354 return;
355 }
Brian Osman00a8b5b2020-10-02 09:06:04 -0400356 fPipelineIntrinsics = std::make_unique<IRIntrinsicMap>(fGPUIntrinsics.get());
Brian Osman8e2ef022020-09-30 13:26:43 -0400357 std::vector<std::unique_ptr<ProgramElement>> pipelineIntrinics;
Brian Osmandd496172020-08-08 08:17:18 -0400358 #if !SKSL_STANDALONE
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400359 {
Ethan Nicholas041fd0a2020-10-07 16:42:04 -0400360 Rehydrator rehydrator(&fIRGenerator->fContext, fIRGenerator->fModifiers.get(),
361 fGpuSymbolTable, this, SKSL_INCLUDE_sksl_pipeline,
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400362 SKSL_INCLUDE_sksl_pipeline_LENGTH);
363 fPipelineSymbolTable = rehydrator.symbolTable();
Brian Osman8e2ef022020-09-30 13:26:43 -0400364 pipelineIntrinics = rehydrator.elements();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -0400365 fModifiers.push_back(fIRGenerator->releaseModifiers());
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400366 }
367 #else
368 this->processIncludeFile(Program::kPipelineStage_Kind, SKSL_PIPELINE_INCLUDE,
Brian Osman8e2ef022020-09-30 13:26:43 -0400369 fGpuSymbolTable, &pipelineIntrinics, &fPipelineSymbolTable);
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400370 #endif
Brian Osman8e2ef022020-09-30 13:26:43 -0400371 grab_intrinsics(&pipelineIntrinics, fPipelineIntrinsics.get());
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400372}
373
374void Compiler::loadInterpreterIntrinsics() {
375 if (fInterpreterSymbolTable) {
376 return;
377 }
Brian Osman00a8b5b2020-10-02 09:06:04 -0400378 fInterpreterIntrinsics = std::make_unique<IRIntrinsicMap>(/*parent=*/nullptr);
379 std::vector<std::unique_ptr<ProgramElement>> interpElements;
Brian Osmandd496172020-08-08 08:17:18 -0400380 #if !SKSL_STANDALONE
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400381 {
Ethan Nicholas041fd0a2020-10-07 16:42:04 -0400382 Rehydrator rehydrator(&fIRGenerator->fContext, fIRGenerator->fModifiers.get(),
383 fRootSymbolTable, this, SKSL_INCLUDE_sksl_interp,
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400384 SKSL_INCLUDE_sksl_interp_LENGTH);
385 fInterpreterSymbolTable = rehydrator.symbolTable();
Brian Osman00a8b5b2020-10-02 09:06:04 -0400386 interpElements = rehydrator.elements();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -0400387 fModifiers.push_back(fIRGenerator->releaseModifiers());
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400388 }
389 #else
390 this->processIncludeFile(Program::kGeneric_Kind, SKSL_INTERP_INCLUDE,
Brian Osman00a8b5b2020-10-02 09:06:04 -0400391 fIRGenerator->fSymbolTable, &interpElements,
Ethan Nicholasb33fa3f2020-08-06 13:00:19 -0400392 &fInterpreterSymbolTable);
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400393 #endif
Brian Osman00a8b5b2020-10-02 09:06:04 -0400394 grab_intrinsics(&interpElements, fInterpreterIntrinsics.get());
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400395}
396
Ethan Nicholasb33fa3f2020-08-06 13:00:19 -0400397void Compiler::processIncludeFile(Program::Kind kind, const char* path,
Ethan Nicholas8da1e652019-05-24 11:01:59 -0400398 std::shared_ptr<SymbolTable> base,
399 std::vector<std::unique_ptr<ProgramElement>>* outElements,
400 std::shared_ptr<SymbolTable>* outSymbolTable) {
Ethan Nicholasb33fa3f2020-08-06 13:00:19 -0400401 std::ifstream in(path);
Brian Osmane498b3c2020-09-23 14:42:11 -0400402 std::unique_ptr<String> text = std::make_unique<String>(std::istreambuf_iterator<char>(in),
403 std::istreambuf_iterator<char>());
Ethan Nicholasb33fa3f2020-08-06 13:00:19 -0400404 if (in.rdstate()) {
405 printf("error reading %s\n", path);
406 abort();
407 }
Brian Osmane498b3c2020-09-23 14:42:11 -0400408 const String* source = fRootSymbolTable->takeOwnershipOfString(std::move(text));
Ethan Nicholasb33fa3f2020-08-06 13:00:19 -0400409 fSource = source;
Ethan Nicholas8da1e652019-05-24 11:01:59 -0400410 Program::Settings settings;
Ethan Nicholasa11035b2019-11-26 16:27:47 -0500411#if !defined(SKSL_STANDALONE) & SK_SUPPORT_GPU
412 GrContextOptions opts;
413 GrShaderCaps caps(opts);
414 settings.fCaps = &caps;
415#endif
John Stiles881a10c2020-09-19 10:13:24 -0400416 SkASSERT(fIRGenerator->fCanInline);
417 fIRGenerator->fCanInline = false;
Brian Osmane498b3c2020-09-23 14:42:11 -0400418 fIRGenerator->start(&settings, base ? base : fRootSymbolTable, nullptr, true);
Ethan Nicholasb33fa3f2020-08-06 13:00:19 -0400419 fIRGenerator->convertProgram(kind, source->c_str(), source->length(), outElements);
John Stiles881a10c2020-09-19 10:13:24 -0400420 fIRGenerator->fCanInline = true;
Ethan Nicholas8da1e652019-05-24 11:01:59 -0400421 if (this->fErrorCount) {
422 printf("Unexpected errors: %s\n", this->fErrorText.c_str());
John Stiles88f3b682020-10-06 13:37:52 -0400423 SkDEBUGFAILF("%s %s\n", path, this->fErrorText.c_str());
Ethan Nicholas8da1e652019-05-24 11:01:59 -0400424 }
Ethan Nicholas8da1e652019-05-24 11:01:59 -0400425 *outSymbolTable = fIRGenerator->fSymbolTable;
Ethan Nicholasa11035b2019-11-26 16:27:47 -0500426#ifdef SK_DEBUG
427 fSource = nullptr;
428#endif
Ethan Nicholas041fd0a2020-10-07 16:42:04 -0400429 fModifiers.push_back(fIRGenerator->releaseModifiers());
Brian Osmane498b3c2020-09-23 14:42:11 -0400430 fIRGenerator->finish();
Ethan Nicholas8da1e652019-05-24 11:01:59 -0400431}
432
ethannicholas22f939e2016-10-13 13:25:34 -0700433// add the definition created by assigning to the lvalue to the definition set
Ethan Nicholas86a43402017-01-19 13:32:00 -0500434void Compiler::addDefinition(const Expression* lvalue, std::unique_ptr<Expression>* expr,
435 DefinitionMap* definitions) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400436 switch (lvalue->kind()) {
437 case Expression::Kind::kVariableReference: {
Brian Osman79457ef2020-09-24 15:01:27 -0400438 const Variable& var = *lvalue->as<VariableReference>().fVariable;
Ethan Nicholas041fd0a2020-10-07 16:42:04 -0400439 if (var.storage() == Variable::kLocal_Storage) {
ethannicholas22f939e2016-10-13 13:25:34 -0700440 (*definitions)[&var] = expr;
441 }
442 break;
443 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400444 case Expression::Kind::kSwizzle:
ethannicholas22f939e2016-10-13 13:25:34 -0700445 // We consider the variable written to as long as at least some of its components have
446 // been written to. This will lead to some false negatives (we won't catch it if you
447 // write to foo.x and then read foo.y), but being stricter could lead to false positives
Mike Klein6ad99092016-10-26 10:35:22 -0400448 // (we write to foo.x, and then pass foo to a function which happens to only read foo.x,
449 // 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 -0700450 // more complicated whole-program analysis. This is probably good enough.
John Stilesa5a97b42020-08-18 11:19:07 -0400451 this->addDefinition(lvalue->as<Swizzle>().fBase.get(),
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400452 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
ethannicholas22f939e2016-10-13 13:25:34 -0700453 definitions);
454 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400455 case Expression::Kind::kIndex:
ethannicholas22f939e2016-10-13 13:25:34 -0700456 // see comments in Swizzle
John Stilesa5a97b42020-08-18 11:19:07 -0400457 this->addDefinition(lvalue->as<IndexExpression>().fBase.get(),
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400458 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
ethannicholas22f939e2016-10-13 13:25:34 -0700459 definitions);
460 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400461 case Expression::Kind::kFieldAccess:
ethannicholas22f939e2016-10-13 13:25:34 -0700462 // see comments in Swizzle
John Stilesa5a97b42020-08-18 11:19:07 -0400463 this->addDefinition(lvalue->as<FieldAccess>().fBase.get(),
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400464 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
ethannicholas22f939e2016-10-13 13:25:34 -0700465 definitions);
466 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400467 case Expression::Kind::kTernary:
Ethan Nicholasa583b812018-01-18 13:32:11 -0500468 // To simplify analysis, we just pretend that we write to both sides of the ternary.
469 // This allows for false positives (meaning we fail to detect that a variable might not
470 // have been assigned), but is preferable to false negatives.
John Stilesa5a97b42020-08-18 11:19:07 -0400471 this->addDefinition(lvalue->as<TernaryExpression>().fIfTrue.get(),
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400472 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
Ethan Nicholasa583b812018-01-18 13:32:11 -0500473 definitions);
John Stilesa5a97b42020-08-18 11:19:07 -0400474 this->addDefinition(lvalue->as<TernaryExpression>().fIfFalse.get(),
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400475 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
Ethan Nicholasa583b812018-01-18 13:32:11 -0500476 definitions);
477 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400478 case Expression::Kind::kExternalValue:
Ethan Nicholas91164d12019-05-15 15:29:54 -0400479 break;
ethannicholas22f939e2016-10-13 13:25:34 -0700480 default:
481 // not an lvalue, can't happen
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400482 SkASSERT(false);
ethannicholas22f939e2016-10-13 13:25:34 -0700483 }
484}
485
486// add local variables defined by this node to the set
Mike Klein6ad99092016-10-26 10:35:22 -0400487void Compiler::addDefinitions(const BasicBlock::Node& node,
Ethan Nicholas86a43402017-01-19 13:32:00 -0500488 DefinitionMap* definitions) {
John Stiles70025e52020-09-28 16:08:58 -0400489 if (node.isExpression()) {
490 Expression* expr = node.expression()->get();
491 switch (expr->kind()) {
492 case Expression::Kind::kBinary: {
493 BinaryExpression* b = &expr->as<BinaryExpression>();
494 if (b->getOperator() == Token::Kind::TK_EQ) {
495 this->addDefinition(&b->left(), &b->rightPointer(), definitions);
496 } else if (Compiler::IsAssignment(b->getOperator())) {
497 this->addDefinition(
498 &b->left(),
499 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
500 definitions);
Ethan Nicholas86a43402017-01-19 13:32:00 -0500501
ethannicholas22f939e2016-10-13 13:25:34 -0700502 }
John Stiles70025e52020-09-28 16:08:58 -0400503 break;
ethannicholas22f939e2016-10-13 13:25:34 -0700504 }
John Stiles70025e52020-09-28 16:08:58 -0400505 case Expression::Kind::kFunctionCall: {
506 const FunctionCall& c = expr->as<FunctionCall>();
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400507 for (size_t i = 0; i < c.function().fParameters.size(); ++i) {
Ethan Nicholas041fd0a2020-10-07 16:42:04 -0400508 if (c.function().fParameters[i]->modifiers().fFlags & Modifiers::kOut_Flag) {
John Stiles70025e52020-09-28 16:08:58 -0400509 this->addDefinition(
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400510 c.arguments()[i].get(),
John Stiles70025e52020-09-28 16:08:58 -0400511 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
512 definitions);
513 }
514 }
515 break;
516 }
517 case Expression::Kind::kPrefix: {
518 const PrefixExpression* p = &expr->as<PrefixExpression>();
519 if (p->fOperator == Token::Kind::TK_MINUSMINUS ||
520 p->fOperator == Token::Kind::TK_PLUSPLUS) {
521 this->addDefinition(
522 p->fOperand.get(),
523 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
524 definitions);
525 }
526 break;
527 }
528 case Expression::Kind::kPostfix: {
529 const PostfixExpression* p = &expr->as<PostfixExpression>();
530 if (p->fOperator == Token::Kind::TK_MINUSMINUS ||
531 p->fOperator == Token::Kind::TK_PLUSPLUS) {
532 this->addDefinition(
533 p->fOperand.get(),
534 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
535 definitions);
536 }
537 break;
538 }
539 case Expression::Kind::kVariableReference: {
540 const VariableReference* v = &expr->as<VariableReference>();
541 if (v->fRefKind != VariableReference::kRead_RefKind) {
542 this->addDefinition(
543 v,
544 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
545 definitions);
546 }
547 break;
548 }
549 default:
550 break;
ethannicholas22f939e2016-10-13 13:25:34 -0700551 }
John Stiles70025e52020-09-28 16:08:58 -0400552 } else if (node.isStatement()) {
553 Statement* stmt = node.statement()->get();
554 if (stmt->is<VarDeclaration>()) {
555 VarDeclaration& vd = stmt->as<VarDeclaration>();
556 if (vd.fValue) {
557 (*definitions)[vd.fVar] = &vd.fValue;
ethannicholas22f939e2016-10-13 13:25:34 -0700558 }
ethannicholas22f939e2016-10-13 13:25:34 -0700559 }
560 }
561}
562
John Stilese6150002020-10-05 12:03:53 -0400563void Compiler::scanCFG(CFG* cfg, BlockId blockId, SkBitSet* processedSet) {
ethannicholas22f939e2016-10-13 13:25:34 -0700564 BasicBlock& block = cfg->fBlocks[blockId];
565
566 // compute definitions after this block
Ethan Nicholas86a43402017-01-19 13:32:00 -0500567 DefinitionMap after = block.fBefore;
ethannicholas22f939e2016-10-13 13:25:34 -0700568 for (const BasicBlock::Node& n : block.fNodes) {
569 this->addDefinitions(n, &after);
570 }
571
572 // propagate definitions to exits
573 for (BlockId exitId : block.fExits) {
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400574 if (exitId == blockId) {
575 continue;
576 }
ethannicholas22f939e2016-10-13 13:25:34 -0700577 BasicBlock& exit = cfg->fBlocks[exitId];
578 for (const auto& pair : after) {
Ethan Nicholas86a43402017-01-19 13:32:00 -0500579 std::unique_ptr<Expression>* e1 = pair.second;
580 auto found = exit.fBefore.find(pair.first);
581 if (found == exit.fBefore.end()) {
John Stilese6150002020-10-05 12:03:53 -0400582 // exit has no definition for it, just copy it and reprocess exit block
583 processedSet->reset(exitId);
ethannicholas22f939e2016-10-13 13:25:34 -0700584 exit.fBefore[pair.first] = e1;
585 } else {
Ethan Nicholas86a43402017-01-19 13:32:00 -0500586 // exit has a (possibly different) value already defined
587 std::unique_ptr<Expression>* e2 = exit.fBefore[pair.first];
ethannicholas22f939e2016-10-13 13:25:34 -0700588 if (e1 != e2) {
John Stilese6150002020-10-05 12:03:53 -0400589 // definition has changed, merge and reprocess the exit block
590 processedSet->reset(exitId);
Ethan Nicholasaf197692017-02-27 13:26:45 -0500591 if (e1 && e2) {
592 exit.fBefore[pair.first] =
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400593 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression;
Ethan Nicholasaf197692017-02-27 13:26:45 -0500594 } else {
595 exit.fBefore[pair.first] = nullptr;
596 }
ethannicholas22f939e2016-10-13 13:25:34 -0700597 }
598 }
599 }
600 }
601}
602
603// returns a map which maps all local variables in the function to null, indicating that their value
604// is initially unknown
Ethan Nicholas86a43402017-01-19 13:32:00 -0500605static DefinitionMap compute_start_state(const CFG& cfg) {
606 DefinitionMap result;
Mike Klein6ad99092016-10-26 10:35:22 -0400607 for (const auto& block : cfg.fBlocks) {
608 for (const auto& node : block.fNodes) {
John Stiles70025e52020-09-28 16:08:58 -0400609 if (node.isStatement()) {
Ethan Nicholascb670962017-04-20 19:31:52 -0400610 const Statement* s = node.statement()->get();
Brian Osmanc0213602020-10-06 14:43:32 -0400611 if (s->is<VarDeclaration>()) {
612 result[s->as<VarDeclaration>().fVar] = nullptr;
ethannicholas22f939e2016-10-13 13:25:34 -0700613 }
614 }
615 }
616 }
617 return result;
618}
619
Ethan Nicholascb670962017-04-20 19:31:52 -0400620/**
621 * Returns true if assigning to this lvalue has no effect.
622 */
623static bool is_dead(const Expression& lvalue) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400624 switch (lvalue.kind()) {
625 case Expression::Kind::kVariableReference:
Brian Osman79457ef2020-09-24 15:01:27 -0400626 return lvalue.as<VariableReference>().fVariable->dead();
Ethan Nicholase6592142020-09-08 10:22:09 -0400627 case Expression::Kind::kSwizzle:
John Stilesa5a97b42020-08-18 11:19:07 -0400628 return is_dead(*lvalue.as<Swizzle>().fBase);
Ethan Nicholase6592142020-09-08 10:22:09 -0400629 case Expression::Kind::kFieldAccess:
John Stilesa5a97b42020-08-18 11:19:07 -0400630 return is_dead(*lvalue.as<FieldAccess>().fBase);
Ethan Nicholase6592142020-09-08 10:22:09 -0400631 case Expression::Kind::kIndex: {
John Stilesa5a97b42020-08-18 11:19:07 -0400632 const IndexExpression& idx = lvalue.as<IndexExpression>();
Ethan Nicholas2a099da2020-01-02 14:40:54 -0500633 return is_dead(*idx.fBase) &&
634 !idx.fIndex->hasProperty(Expression::Property::kSideEffects);
Ethan Nicholascb670962017-04-20 19:31:52 -0400635 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400636 case Expression::Kind::kTernary: {
John Stilesa5a97b42020-08-18 11:19:07 -0400637 const TernaryExpression& t = lvalue.as<TernaryExpression>();
Ethan Nicholasa583b812018-01-18 13:32:11 -0500638 return !t.fTest->hasSideEffects() && is_dead(*t.fIfTrue) && is_dead(*t.fIfFalse);
639 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400640 case Expression::Kind::kExternalValue:
Ethan Nicholas91164d12019-05-15 15:29:54 -0400641 return false;
Ethan Nicholascb670962017-04-20 19:31:52 -0400642 default:
Ethan Nicholas2a099da2020-01-02 14:40:54 -0500643#ifdef SK_DEBUG
Ethan Nicholascb670962017-04-20 19:31:52 -0400644 ABORT("invalid lvalue: %s\n", lvalue.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -0500645#endif
646 return false;
Ethan Nicholascb670962017-04-20 19:31:52 -0400647 }
648}
ethannicholas22f939e2016-10-13 13:25:34 -0700649
Ethan Nicholascb670962017-04-20 19:31:52 -0400650/**
651 * Returns true if this is an assignment which can be collapsed down to just the right hand side due
652 * to a dead target and lack of side effects on the left hand side.
653 */
654static bool dead_assignment(const BinaryExpression& b) {
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400655 if (!Compiler::IsAssignment(b.getOperator())) {
Ethan Nicholascb670962017-04-20 19:31:52 -0400656 return false;
657 }
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400658 return is_dead(b.left());
Ethan Nicholascb670962017-04-20 19:31:52 -0400659}
660
661void Compiler::computeDataFlow(CFG* cfg) {
662 cfg->fBlocks[cfg->fStart].fBefore = compute_start_state(*cfg);
John Stilese6150002020-10-05 12:03:53 -0400663
664 // We set bits in the "processed" set after a block has been scanned.
665 SkBitSet processedSet(cfg->fBlocks.size());
666 while (SkBitSet::OptionalIndex blockId = processedSet.findFirstUnset()) {
667 processedSet.set(*blockId);
668 this->scanCFG(cfg, *blockId, &processedSet);
ethannicholas22f939e2016-10-13 13:25:34 -0700669 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400670}
671
672/**
673 * Attempts to replace the expression pointed to by iter with a new one (in both the CFG and the
674 * IR). If the expression can be cleanly removed, returns true and updates the iterator to point to
675 * the newly-inserted element. Otherwise updates only the IR and returns false (and the CFG will
676 * need to be regenerated).
677 */
John Stilesafbf8992020-08-18 10:08:21 -0400678static bool try_replace_expression(BasicBlock* b,
679 std::vector<BasicBlock::Node>::iterator* iter,
680 std::unique_ptr<Expression>* newExpression) {
Ethan Nicholascb670962017-04-20 19:31:52 -0400681 std::unique_ptr<Expression>* target = (*iter)->expression();
682 if (!b->tryRemoveExpression(iter)) {
683 *target = std::move(*newExpression);
684 return false;
685 }
686 *target = std::move(*newExpression);
687 return b->tryInsertExpression(iter, target);
688}
689
690/**
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400691 * Returns true if the expression is a constant numeric literal with the specified value, or a
692 * constant vector with all elements equal to the specified value.
Ethan Nicholascb670962017-04-20 19:31:52 -0400693 */
Ethan Nicholasa3f22f12020-10-01 12:13:17 -0400694template <typename T = SKSL_FLOAT>
John Stiles9d944232020-08-19 09:56:49 -0400695static bool is_constant(const Expression& expr, T value) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400696 switch (expr.kind()) {
697 case Expression::Kind::kIntLiteral:
Ethan Nicholase96cdd12020-09-28 16:27:18 -0400698 return expr.as<IntLiteral>().value() == value;
John Stiles9d944232020-08-19 09:56:49 -0400699
Ethan Nicholase6592142020-09-08 10:22:09 -0400700 case Expression::Kind::kFloatLiteral:
Ethan Nicholasa3f22f12020-10-01 12:13:17 -0400701 return expr.as<FloatLiteral>().value() == value;
John Stiles9d944232020-08-19 09:56:49 -0400702
Ethan Nicholase6592142020-09-08 10:22:09 -0400703 case Expression::Kind::kConstructor: {
John Stiles9d944232020-08-19 09:56:49 -0400704 const Constructor& constructor = expr.as<Constructor>();
705 if (constructor.isCompileTimeConstant()) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400706 const Type& constructorType = constructor.type();
707 bool isFloat = constructorType.columns() > 1
708 ? constructorType.componentType().isFloat()
709 : constructorType.isFloat();
710 switch (constructorType.typeKind()) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400711 case Type::TypeKind::kVector:
Ethan Nicholas30d30222020-09-11 12:27:26 -0400712 for (int i = 0; i < constructorType.columns(); ++i) {
John Stiles9d944232020-08-19 09:56:49 -0400713 if (isFloat) {
714 if (constructor.getFVecComponent(i) != value) {
715 return false;
716 }
717 } else {
718 if (constructor.getIVecComponent(i) != value) {
719 return false;
720 }
721 }
Ethan Nicholasd188c182019-06-10 15:55:38 -0400722 }
John Stiles9d944232020-08-19 09:56:49 -0400723 return true;
724
Ethan Nicholase6592142020-09-08 10:22:09 -0400725 case Type::TypeKind::kScalar:
Ethan Nicholasf70f0442020-09-29 12:41:35 -0400726 SkASSERT(constructor.arguments().size() == 1);
727 return is_constant<T>(*constructor.arguments()[0], value);
John Stiles9d944232020-08-19 09:56:49 -0400728
729 default:
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400730 return false;
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400731 }
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400732 }
733 return false;
734 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400735 default:
736 return false;
737 }
738}
739
740/**
741 * Collapses the binary expression pointed to by iter down to just the right side (in both the IR
742 * and CFG structures).
743 */
John Stilesafbf8992020-08-18 10:08:21 -0400744static void delete_left(BasicBlock* b,
745 std::vector<BasicBlock::Node>::iterator* iter,
746 bool* outUpdated,
747 bool* outNeedsRescan) {
Ethan Nicholascb670962017-04-20 19:31:52 -0400748 *outUpdated = true;
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400749 std::unique_ptr<Expression>* target = (*iter)->expression();
John Stilesa5a97b42020-08-18 11:19:07 -0400750 BinaryExpression& bin = (*target)->as<BinaryExpression>();
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400751 Expression& left = bin.left();
752 std::unique_ptr<Expression>& rightPointer = bin.rightPointer();
753 SkASSERT(!left.hasSideEffects());
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400754 bool result;
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400755 if (bin.getOperator() == Token::Kind::TK_EQ) {
756 result = b->tryRemoveLValueBefore(iter, &left);
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400757 } else {
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400758 result = b->tryRemoveExpressionBefore(iter, &left);
Ethan Nicholascb670962017-04-20 19:31:52 -0400759 }
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400760 *target = std::move(rightPointer);
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400761 if (!result) {
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400762 *outNeedsRescan = true;
763 return;
764 }
765 if (*iter == b->fNodes.begin()) {
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400766 *outNeedsRescan = true;
767 return;
768 }
769 --(*iter);
John Stiles70025e52020-09-28 16:08:58 -0400770 if (!(*iter)->isExpression() || (*iter)->expression() != &rightPointer) {
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400771 *outNeedsRescan = true;
772 return;
773 }
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400774 *iter = b->fNodes.erase(*iter);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400775 SkASSERT((*iter)->expression() == target);
Ethan Nicholascb670962017-04-20 19:31:52 -0400776}
777
778/**
779 * Collapses the binary expression pointed to by iter down to just the left side (in both the IR and
780 * CFG structures).
781 */
John Stilesafbf8992020-08-18 10:08:21 -0400782static void delete_right(BasicBlock* b,
783 std::vector<BasicBlock::Node>::iterator* iter,
784 bool* outUpdated,
785 bool* outNeedsRescan) {
Ethan Nicholascb670962017-04-20 19:31:52 -0400786 *outUpdated = true;
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400787 std::unique_ptr<Expression>* target = (*iter)->expression();
John Stilesa5a97b42020-08-18 11:19:07 -0400788 BinaryExpression& bin = (*target)->as<BinaryExpression>();
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400789 std::unique_ptr<Expression>& leftPointer = bin.leftPointer();
790 Expression& right = bin.right();
791 SkASSERT(!right.hasSideEffects());
792 if (!b->tryRemoveExpressionBefore(iter, &right)) {
793 *target = std::move(leftPointer);
Ethan Nicholascb670962017-04-20 19:31:52 -0400794 *outNeedsRescan = true;
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400795 return;
Ethan Nicholascb670962017-04-20 19:31:52 -0400796 }
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400797 *target = std::move(leftPointer);
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400798 if (*iter == b->fNodes.begin()) {
799 *outNeedsRescan = true;
800 return;
801 }
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400802 --(*iter);
John Stiles70025e52020-09-28 16:08:58 -0400803 if ((!(*iter)->isExpression() || (*iter)->expression() != &leftPointer)) {
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400804 *outNeedsRescan = true;
805 return;
806 }
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400807 *iter = b->fNodes.erase(*iter);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400808 SkASSERT((*iter)->expression() == target);
Ethan Nicholascb670962017-04-20 19:31:52 -0400809}
810
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400811/**
812 * Constructs the specified type using a single argument.
813 */
Ethan Nicholas30d30222020-09-11 12:27:26 -0400814static std::unique_ptr<Expression> construct(const Type* type, std::unique_ptr<Expression> v) {
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400815 std::vector<std::unique_ptr<Expression>> args;
816 args.push_back(std::move(v));
Ethan Nicholase6592142020-09-08 10:22:09 -0400817 std::unique_ptr<Expression> result = std::make_unique<Constructor>(-1, type, std::move(args));
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400818 return result;
819}
820
821/**
822 * Used in the implementations of vectorize_left and vectorize_right. Given a vector type and an
823 * expression x, deletes the expression pointed to by iter and replaces it with <type>(x).
824 */
825static void vectorize(BasicBlock* b,
826 std::vector<BasicBlock::Node>::iterator* iter,
827 const Type& type,
828 std::unique_ptr<Expression>* otherExpression,
829 bool* outUpdated,
830 bool* outNeedsRescan) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400831 SkASSERT((*(*iter)->expression())->kind() == Expression::Kind::kBinary);
832 SkASSERT(type.typeKind() == Type::TypeKind::kVector);
Ethan Nicholas30d30222020-09-11 12:27:26 -0400833 SkASSERT((*otherExpression)->type().typeKind() == Type::TypeKind::kScalar);
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400834 *outUpdated = true;
835 std::unique_ptr<Expression>* target = (*iter)->expression();
836 if (!b->tryRemoveExpression(iter)) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400837 *target = construct(&type, std::move(*otherExpression));
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400838 *outNeedsRescan = true;
839 } else {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400840 *target = construct(&type, std::move(*otherExpression));
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400841 if (!b->tryInsertExpression(iter, target)) {
842 *outNeedsRescan = true;
843 }
844 }
845}
846
847/**
848 * Given a binary expression of the form x <op> vec<n>(y), deletes the right side and vectorizes the
849 * left to yield vec<n>(x).
850 */
851static void vectorize_left(BasicBlock* b,
852 std::vector<BasicBlock::Node>::iterator* iter,
853 bool* outUpdated,
854 bool* outNeedsRescan) {
John Stilesa5a97b42020-08-18 11:19:07 -0400855 BinaryExpression& bin = (*(*iter)->expression())->as<BinaryExpression>();
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400856 vectorize(b, iter, bin.right().type(), &bin.leftPointer(), outUpdated, outNeedsRescan);
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400857}
858
859/**
860 * Given a binary expression of the form vec<n>(x) <op> y, deletes the left side and vectorizes the
861 * right to yield vec<n>(y).
862 */
863static void vectorize_right(BasicBlock* b,
864 std::vector<BasicBlock::Node>::iterator* iter,
865 bool* outUpdated,
866 bool* outNeedsRescan) {
John Stilesa5a97b42020-08-18 11:19:07 -0400867 BinaryExpression& bin = (*(*iter)->expression())->as<BinaryExpression>();
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400868 vectorize(b, iter, bin.left().type(), &bin.rightPointer(), outUpdated, outNeedsRescan);
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400869}
870
871// Mark that an expression which we were writing to is no longer being written to
John Stilesa5a97b42020-08-18 11:19:07 -0400872static void clear_write(Expression& expr) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400873 switch (expr.kind()) {
874 case Expression::Kind::kVariableReference: {
John Stilesa5a97b42020-08-18 11:19:07 -0400875 expr.as<VariableReference>().setRefKind(VariableReference::kRead_RefKind);
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400876 break;
877 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400878 case Expression::Kind::kFieldAccess:
John Stilesa5a97b42020-08-18 11:19:07 -0400879 clear_write(*expr.as<FieldAccess>().fBase);
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400880 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400881 case Expression::Kind::kSwizzle:
John Stilesa5a97b42020-08-18 11:19:07 -0400882 clear_write(*expr.as<Swizzle>().fBase);
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400883 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400884 case Expression::Kind::kIndex:
John Stilesa5a97b42020-08-18 11:19:07 -0400885 clear_write(*expr.as<IndexExpression>().fBase);
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400886 break;
887 default:
888 ABORT("shouldn't be writing to this kind of expression\n");
889 break;
890 }
891}
892
Ethan Nicholascb670962017-04-20 19:31:52 -0400893void Compiler::simplifyExpression(DefinitionMap& definitions,
894 BasicBlock& b,
895 std::vector<BasicBlock::Node>::iterator* iter,
896 std::unordered_set<const Variable*>* undefinedVariables,
897 bool* outUpdated,
898 bool* outNeedsRescan) {
899 Expression* expr = (*iter)->expression()->get();
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400900 SkASSERT(expr);
Ethan Nicholascb670962017-04-20 19:31:52 -0400901 if ((*iter)->fConstantPropagation) {
902 std::unique_ptr<Expression> optimized = expr->constantPropagate(*fIRGenerator, definitions);
903 if (optimized) {
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400904 *outUpdated = true;
Ethan Nicholas30d30222020-09-11 12:27:26 -0400905 optimized = fIRGenerator->coerce(std::move(optimized), expr->type());
Ethan Nicholas1d881522020-09-11 09:32:54 -0400906 SkASSERT(optimized);
Ethan Nicholascb670962017-04-20 19:31:52 -0400907 if (!try_replace_expression(&b, iter, &optimized)) {
908 *outNeedsRescan = true;
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400909 return;
Ethan Nicholascb670962017-04-20 19:31:52 -0400910 }
John Stiles70025e52020-09-28 16:08:58 -0400911 SkASSERT((*iter)->isExpression());
Ethan Nicholascb670962017-04-20 19:31:52 -0400912 expr = (*iter)->expression()->get();
Ethan Nicholascb670962017-04-20 19:31:52 -0400913 }
914 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400915 switch (expr->kind()) {
916 case Expression::Kind::kVariableReference: {
John Stilesa5a97b42020-08-18 11:19:07 -0400917 const VariableReference& ref = expr->as<VariableReference>();
Brian Osman79457ef2020-09-24 15:01:27 -0400918 const Variable* var = ref.fVariable;
Ethan Nicholas8f7e28f2018-03-26 14:24:27 -0400919 if (ref.refKind() != VariableReference::kWrite_RefKind &&
920 ref.refKind() != VariableReference::kPointer_RefKind &&
Ethan Nicholas041fd0a2020-10-07 16:42:04 -0400921 var->storage() == Variable::kLocal_Storage && !definitions[var] &&
Brian Osman79457ef2020-09-24 15:01:27 -0400922 (*undefinedVariables).find(var) == (*undefinedVariables).end()) {
923 (*undefinedVariables).insert(var);
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000924 this->error(expr->fOffset,
Ethan Nicholase2c49992020-10-05 11:49:11 -0400925 "'" + var->name() + "' has not been assigned");
Ethan Nicholascb670962017-04-20 19:31:52 -0400926 }
927 break;
928 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400929 case Expression::Kind::kTernary: {
John Stiles403a3632020-08-20 12:11:48 -0400930 TernaryExpression* t = &expr->as<TernaryExpression>();
Ethan Nicholase6592142020-09-08 10:22:09 -0400931 if (t->fTest->kind() == Expression::Kind::kBoolLiteral) {
Ethan Nicholascb670962017-04-20 19:31:52 -0400932 // ternary has a constant test, replace it with either the true or
933 // false branch
Ethan Nicholas59d660c2020-09-28 09:18:15 -0400934 if (t->fTest->as<BoolLiteral>().value()) {
Ethan Nicholascb670962017-04-20 19:31:52 -0400935 (*iter)->setExpression(std::move(t->fIfTrue));
936 } else {
937 (*iter)->setExpression(std::move(t->fIfFalse));
938 }
939 *outUpdated = true;
940 *outNeedsRescan = true;
941 }
942 break;
943 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400944 case Expression::Kind::kBinary: {
John Stiles403a3632020-08-20 12:11:48 -0400945 BinaryExpression* bin = &expr->as<BinaryExpression>();
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400946 if (dead_assignment(*bin)) {
947 delete_left(&b, iter, outUpdated, outNeedsRescan);
948 break;
949 }
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400950 Expression& left = bin->left();
951 Expression& right = bin->right();
952 const Type& leftType = left.type();
953 const Type& rightType = right.type();
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400954 // collapse useless expressions like x * 1 or x + 0
Ethan Nicholas30d30222020-09-11 12:27:26 -0400955 if (((leftType.typeKind() != Type::TypeKind::kScalar) &&
956 (leftType.typeKind() != Type::TypeKind::kVector)) ||
957 ((rightType.typeKind() != Type::TypeKind::kScalar) &&
958 (rightType.typeKind() != Type::TypeKind::kVector))) {
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400959 break;
960 }
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400961 switch (bin->getOperator()) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400962 case Token::Kind::TK_STAR:
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400963 if (is_constant(left, 1)) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400964 if (leftType.typeKind() == Type::TypeKind::kVector &&
965 rightType.typeKind() == Type::TypeKind::kScalar) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400966 // float4(1) * x -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400967 vectorize_right(&b, iter, outUpdated, outNeedsRescan);
968 } else {
969 // 1 * x -> x
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400970 // 1 * float4(x) -> float4(x)
971 // float4(1) * float4(x) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400972 delete_left(&b, iter, outUpdated, outNeedsRescan);
973 }
974 }
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400975 else if (is_constant(left, 0)) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400976 if (leftType.typeKind() == Type::TypeKind::kScalar &&
977 rightType.typeKind() == Type::TypeKind::kVector &&
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400978 !right.hasSideEffects()) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400979 // 0 * float4(x) -> float4(0)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400980 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
981 } else {
982 // 0 * x -> 0
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400983 // float4(0) * x -> float4(0)
984 // float4(0) * float4(x) -> float4(0)
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400985 if (!right.hasSideEffects()) {
Ethan Nicholas51493ee2017-12-11 12:34:33 -0500986 delete_right(&b, iter, outUpdated, outNeedsRescan);
987 }
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400988 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400989 }
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400990 else if (is_constant(right, 1)) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400991 if (leftType.typeKind() == Type::TypeKind::kScalar &&
992 rightType.typeKind() == Type::TypeKind::kVector) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400993 // x * float4(1) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400994 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
995 } else {
996 // x * 1 -> x
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400997 // float4(x) * 1 -> float4(x)
998 // float4(x) * float4(1) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400999 delete_right(&b, iter, outUpdated, outNeedsRescan);
1000 }
1001 }
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001002 else if (is_constant(right, 0)) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04001003 if (leftType.typeKind() == Type::TypeKind::kVector &&
1004 rightType.typeKind() == Type::TypeKind::kScalar &&
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001005 !left.hasSideEffects()) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -04001006 // float4(x) * 0 -> float4(0)
Ethan Nicholasfe53e582017-04-27 16:24:51 -04001007 vectorize_right(&b, iter, outUpdated, outNeedsRescan);
1008 } else {
1009 // x * 0 -> 0
Ethan Nicholas5af9ea32017-07-28 15:19:46 -04001010 // x * float4(0) -> float4(0)
1011 // float4(x) * float4(0) -> float4(0)
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001012 if (!left.hasSideEffects()) {
Ethan Nicholas51493ee2017-12-11 12:34:33 -05001013 delete_left(&b, iter, outUpdated, outNeedsRescan);
1014 }
Ethan Nicholasfe53e582017-04-27 16:24:51 -04001015 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001016 }
1017 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001018 case Token::Kind::TK_PLUS:
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001019 if (is_constant(left, 0)) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04001020 if (leftType.typeKind() == Type::TypeKind::kVector &&
1021 rightType.typeKind() == Type::TypeKind::kScalar) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -04001022 // float4(0) + x -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -04001023 vectorize_right(&b, iter, outUpdated, outNeedsRescan);
1024 } else {
1025 // 0 + x -> x
Ethan Nicholas5af9ea32017-07-28 15:19:46 -04001026 // 0 + float4(x) -> float4(x)
1027 // float4(0) + float4(x) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -04001028 delete_left(&b, iter, outUpdated, outNeedsRescan);
1029 }
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001030 } else if (is_constant(right, 0)) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04001031 if (leftType.typeKind() == Type::TypeKind::kScalar &&
1032 rightType.typeKind() == Type::TypeKind::kVector) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -04001033 // x + float4(0) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -04001034 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
1035 } else {
1036 // x + 0 -> x
Ethan Nicholas5af9ea32017-07-28 15:19:46 -04001037 // float4(x) + 0 -> float4(x)
1038 // float4(x) + float4(0) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -04001039 delete_right(&b, iter, outUpdated, outNeedsRescan);
1040 }
Ethan Nicholas56e42712017-04-21 10:23:37 -04001041 }
1042 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001043 case Token::Kind::TK_MINUS:
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001044 if (is_constant(right, 0)) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04001045 if (leftType.typeKind() == Type::TypeKind::kScalar &&
1046 rightType.typeKind() == Type::TypeKind::kVector) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -04001047 // x - float4(0) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -04001048 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
1049 } else {
1050 // x - 0 -> x
Ethan Nicholas5af9ea32017-07-28 15:19:46 -04001051 // float4(x) - 0 -> float4(x)
1052 // float4(x) - float4(0) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -04001053 delete_right(&b, iter, outUpdated, outNeedsRescan);
1054 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001055 }
1056 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001057 case Token::Kind::TK_SLASH:
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001058 if (is_constant(right, 1)) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04001059 if (leftType.typeKind() == Type::TypeKind::kScalar &&
1060 rightType.typeKind() == Type::TypeKind::kVector) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -04001061 // x / float4(1) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -04001062 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
1063 } else {
1064 // x / 1 -> x
Ethan Nicholas5af9ea32017-07-28 15:19:46 -04001065 // float4(x) / 1 -> float4(x)
1066 // float4(x) / float4(1) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -04001067 delete_right(&b, iter, outUpdated, outNeedsRescan);
1068 }
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001069 } else if (is_constant(left, 0)) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04001070 if (leftType.typeKind() == Type::TypeKind::kScalar &&
1071 rightType.typeKind() == Type::TypeKind::kVector &&
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001072 !right.hasSideEffects()) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -04001073 // 0 / float4(x) -> float4(0)
Ethan Nicholasfe53e582017-04-27 16:24:51 -04001074 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
1075 } else {
1076 // 0 / x -> 0
Ethan Nicholas5af9ea32017-07-28 15:19:46 -04001077 // float4(0) / x -> float4(0)
1078 // float4(0) / float4(x) -> float4(0)
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001079 if (!right.hasSideEffects()) {
Ethan Nicholas51493ee2017-12-11 12:34:33 -05001080 delete_right(&b, iter, outUpdated, outNeedsRescan);
1081 }
Ethan Nicholasfe53e582017-04-27 16:24:51 -04001082 }
1083 }
1084 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001085 case Token::Kind::TK_PLUSEQ:
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001086 if (is_constant(right, 0)) {
1087 clear_write(left);
Ethan Nicholasfe53e582017-04-27 16:24:51 -04001088 delete_right(&b, iter, outUpdated, outNeedsRescan);
1089 }
1090 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001091 case Token::Kind::TK_MINUSEQ:
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001092 if (is_constant(right, 0)) {
1093 clear_write(left);
Ethan Nicholasfe53e582017-04-27 16:24:51 -04001094 delete_right(&b, iter, outUpdated, outNeedsRescan);
1095 }
1096 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001097 case Token::Kind::TK_STAREQ:
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001098 if (is_constant(right, 1)) {
1099 clear_write(left);
Ethan Nicholasfe53e582017-04-27 16:24:51 -04001100 delete_right(&b, iter, outUpdated, outNeedsRescan);
1101 }
1102 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001103 case Token::Kind::TK_SLASHEQ:
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001104 if (is_constant(right, 1)) {
1105 clear_write(left);
Ethan Nicholascb670962017-04-20 19:31:52 -04001106 delete_right(&b, iter, outUpdated, outNeedsRescan);
1107 }
1108 break;
1109 default:
1110 break;
1111 }
Ethan Nicholas409f6f02019-09-17 12:34:39 -04001112 break;
1113 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001114 case Expression::Kind::kSwizzle: {
John Stiles403a3632020-08-20 12:11:48 -04001115 Swizzle& s = expr->as<Swizzle>();
Ethan Nicholas409f6f02019-09-17 12:34:39 -04001116 // detect identity swizzles like foo.rgba
Ethan Nicholas30d30222020-09-11 12:27:26 -04001117 if ((int) s.fComponents.size() == s.fBase->type().columns()) {
Ethan Nicholas409f6f02019-09-17 12:34:39 -04001118 bool identity = true;
1119 for (int i = 0; i < (int) s.fComponents.size(); ++i) {
1120 if (s.fComponents[i] != i) {
1121 identity = false;
1122 break;
1123 }
1124 }
1125 if (identity) {
1126 *outUpdated = true;
1127 if (!try_replace_expression(&b, iter, &s.fBase)) {
1128 *outNeedsRescan = true;
1129 return;
1130 }
John Stiles70025e52020-09-28 16:08:58 -04001131 SkASSERT((*iter)->isExpression());
Ethan Nicholas409f6f02019-09-17 12:34:39 -04001132 break;
1133 }
1134 }
1135 // detect swizzles of swizzles, e.g. replace foo.argb.r000 with foo.a000
Ethan Nicholase6592142020-09-08 10:22:09 -04001136 if (s.fBase->kind() == Expression::Kind::kSwizzle) {
John Stilesa5a97b42020-08-18 11:19:07 -04001137 Swizzle& base = s.fBase->as<Swizzle>();
Ethan Nicholas409f6f02019-09-17 12:34:39 -04001138 std::vector<int> final;
1139 for (int c : s.fComponents) {
Brian Osman25647672020-09-15 15:16:56 -04001140 final.push_back(base.fComponents[c]);
Ethan Nicholas409f6f02019-09-17 12:34:39 -04001141 }
1142 *outUpdated = true;
1143 std::unique_ptr<Expression> replacement(new Swizzle(*fContext, base.fBase->clone(),
1144 std::move(final)));
1145 if (!try_replace_expression(&b, iter, &replacement)) {
1146 *outNeedsRescan = true;
1147 return;
1148 }
John Stiles70025e52020-09-28 16:08:58 -04001149 SkASSERT((*iter)->isExpression());
Ethan Nicholas409f6f02019-09-17 12:34:39 -04001150 }
John Stiles30212b72020-06-11 17:55:07 -04001151 break;
Ethan Nicholascb670962017-04-20 19:31:52 -04001152 }
1153 default:
1154 break;
1155 }
1156}
1157
John Stiles92219b42020-06-15 12:32:24 -04001158// Returns true if this statement could potentially execute a break at the current level. We ignore
1159// nested loops and switches, since any breaks inside of them will merely break the loop / switch.
John Stilesb92641c2020-08-31 18:09:01 -04001160static bool contains_conditional_break(Statement& stmt) {
1161 class ContainsConditionalBreak : public ProgramVisitor {
1162 public:
1163 bool visitStatement(const Statement& stmt) override {
Ethan Nicholase6592142020-09-08 10:22:09 -04001164 switch (stmt.kind()) {
1165 case Statement::Kind::kBlock:
John Stilesb92641c2020-08-31 18:09:01 -04001166 return this->INHERITED::visitStatement(stmt);
1167
Ethan Nicholase6592142020-09-08 10:22:09 -04001168 case Statement::Kind::kBreak:
John Stilesb92641c2020-08-31 18:09:01 -04001169 return fInConditional > 0;
1170
Ethan Nicholase6592142020-09-08 10:22:09 -04001171 case Statement::Kind::kIf: {
John Stilesb92641c2020-08-31 18:09:01 -04001172 ++fInConditional;
1173 bool result = this->INHERITED::visitStatement(stmt);
1174 --fInConditional;
1175 return result;
1176 }
1177
1178 default:
1179 return false;
1180 }
1181 }
1182
1183 int fInConditional = 0;
1184 using INHERITED = ProgramVisitor;
1185 };
1186
1187 return ContainsConditionalBreak{}.visitStatement(stmt);
John Stiles92219b42020-06-15 12:32:24 -04001188}
1189
Ethan Nicholas5005a222018-08-24 13:06:27 -04001190// returns true if this statement definitely executes a break at the current level (we ignore
1191// nested loops and switches, since any breaks inside of them will merely break the loop / switch)
John Stilesb92641c2020-08-31 18:09:01 -04001192static bool contains_unconditional_break(Statement& stmt) {
1193 class ContainsUnconditionalBreak : public ProgramVisitor {
1194 public:
1195 bool visitStatement(const Statement& stmt) override {
Ethan Nicholase6592142020-09-08 10:22:09 -04001196 switch (stmt.kind()) {
1197 case Statement::Kind::kBlock:
John Stilesb92641c2020-08-31 18:09:01 -04001198 return this->INHERITED::visitStatement(stmt);
1199
Ethan Nicholase6592142020-09-08 10:22:09 -04001200 case Statement::Kind::kBreak:
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001201 return true;
John Stilesb92641c2020-08-31 18:09:01 -04001202
1203 default:
1204 return false;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001205 }
John Stilesb92641c2020-08-31 18:09:01 -04001206 }
John Stiles92219b42020-06-15 12:32:24 -04001207
John Stilesb92641c2020-08-31 18:09:01 -04001208 using INHERITED = ProgramVisitor;
1209 };
John Stiles92219b42020-06-15 12:32:24 -04001210
John Stilesb92641c2020-08-31 18:09:01 -04001211 return ContainsUnconditionalBreak{}.visitStatement(stmt);
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001212}
1213
John Stiles92219b42020-06-15 12:32:24 -04001214static void move_all_but_break(std::unique_ptr<Statement>& stmt,
1215 std::vector<std::unique_ptr<Statement>>* target) {
Ethan Nicholase6592142020-09-08 10:22:09 -04001216 switch (stmt->kind()) {
1217 case Statement::Kind::kBlock: {
John Stiles92219b42020-06-15 12:32:24 -04001218 // Recurse into the block.
1219 Block& block = static_cast<Block&>(*stmt);
1220
1221 std::vector<std::unique_ptr<Statement>> blockStmts;
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001222 blockStmts.reserve(block.children().size());
1223 for (std::unique_ptr<Statement>& stmt : block.children()) {
1224 move_all_but_break(stmt, &blockStmts);
Ethan Nicholas739e1ca2020-06-11 12:16:14 -04001225 }
John Stiles92219b42020-06-15 12:32:24 -04001226
1227 target->push_back(std::make_unique<Block>(block.fOffset, std::move(blockStmts),
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001228 block.symbolTable(), block.isScope()));
Ethan Nicholas739e1ca2020-06-11 12:16:14 -04001229 break;
John Stiles92219b42020-06-15 12:32:24 -04001230 }
1231
Ethan Nicholase6592142020-09-08 10:22:09 -04001232 case Statement::Kind::kBreak:
John Stiles92219b42020-06-15 12:32:24 -04001233 // Do not append a break to the target.
1234 break;
1235
Ethan Nicholas739e1ca2020-06-11 12:16:14 -04001236 default:
John Stiles92219b42020-06-15 12:32:24 -04001237 // Append normal statements to the target.
1238 target->push_back(std::move(stmt));
1239 break;
Ethan Nicholas739e1ca2020-06-11 12:16:14 -04001240 }
1241}
1242
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001243// Returns a block containing all of the statements that will be run if the given case matches
1244// (which, owing to the statements being owned by unique_ptrs, means the switch itself will be
1245// broken by this call and must then be discarded).
1246// Returns null (and leaves the switch unmodified) if no such simple reduction is possible, such as
1247// when break statements appear inside conditionals.
John Stiles92219b42020-06-15 12:32:24 -04001248static std::unique_ptr<Statement> block_for_case(SwitchStatement* switchStatement,
1249 SwitchCase* caseToCapture) {
1250 // We have to be careful to not move any of the pointers until after we're sure we're going to
1251 // succeed, so before we make any changes at all, we check the switch-cases to decide on a plan
1252 // of action. First, find the switch-case we are interested in.
1253 auto iter = switchStatement->fCases.begin();
1254 for (; iter != switchStatement->fCases.end(); ++iter) {
1255 if (iter->get() == caseToCapture) {
1256 break;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001257 }
John Stiles92219b42020-06-15 12:32:24 -04001258 }
1259
1260 // Next, walk forward through the rest of the switch. If we find a conditional break, we're
1261 // stuck and can't simplify at all. If we find an unconditional break, we have a range of
1262 // statements that we can use for simplification.
1263 auto startIter = iter;
1264 Statement* unconditionalBreakStmt = nullptr;
1265 for (; iter != switchStatement->fCases.end(); ++iter) {
1266 for (std::unique_ptr<Statement>& stmt : (*iter)->fStatements) {
1267 if (contains_conditional_break(*stmt)) {
1268 // We can't reduce switch-cases to a block when they have conditional breaks.
1269 return nullptr;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001270 }
John Stiles92219b42020-06-15 12:32:24 -04001271
1272 if (contains_unconditional_break(*stmt)) {
1273 // We found an unconditional break. We can use this block, but we need to strip
1274 // out the break statement.
1275 unconditionalBreakStmt = stmt.get();
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001276 break;
1277 }
1278 }
John Stiles92219b42020-06-15 12:32:24 -04001279
1280 if (unconditionalBreakStmt != nullptr) {
1281 break;
1282 }
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001283 }
John Stiles92219b42020-06-15 12:32:24 -04001284
1285 // We fell off the bottom of the switch or encountered a break. We know the range of statements
1286 // that we need to move over, and we know it's safe to do so.
1287 std::vector<std::unique_ptr<Statement>> caseStmts;
1288
1289 // We can move over most of the statements as-is.
1290 while (startIter != iter) {
1291 for (std::unique_ptr<Statement>& stmt : (*startIter)->fStatements) {
1292 caseStmts.push_back(std::move(stmt));
1293 }
1294 ++startIter;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001295 }
John Stiles92219b42020-06-15 12:32:24 -04001296
1297 // If we found an unconditional break at the end, we need to move what we can while avoiding
1298 // that break.
1299 if (unconditionalBreakStmt != nullptr) {
1300 for (std::unique_ptr<Statement>& stmt : (*startIter)->fStatements) {
1301 if (stmt.get() == unconditionalBreakStmt) {
1302 move_all_but_break(stmt, &caseStmts);
1303 unconditionalBreakStmt = nullptr;
1304 break;
1305 }
1306
1307 caseStmts.push_back(std::move(stmt));
1308 }
1309 }
1310
1311 SkASSERT(unconditionalBreakStmt == nullptr); // Verify that we fixed the unconditional break.
1312
1313 // Return our newly-synthesized block.
1314 return std::make_unique<Block>(/*offset=*/-1, std::move(caseStmts), switchStatement->fSymbols);
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001315}
1316
Ethan Nicholascb670962017-04-20 19:31:52 -04001317void Compiler::simplifyStatement(DefinitionMap& definitions,
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001318 BasicBlock& b,
1319 std::vector<BasicBlock::Node>::iterator* iter,
1320 std::unordered_set<const Variable*>* undefinedVariables,
1321 bool* outUpdated,
1322 bool* outNeedsRescan) {
Ethan Nicholascb670962017-04-20 19:31:52 -04001323 Statement* stmt = (*iter)->statement()->get();
Ethan Nicholase6592142020-09-08 10:22:09 -04001324 switch (stmt->kind()) {
1325 case Statement::Kind::kVarDeclaration: {
John Stilesa5a97b42020-08-18 11:19:07 -04001326 const auto& varDecl = stmt->as<VarDeclaration>();
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001327 if (varDecl.fVar->dead() &&
1328 (!varDecl.fValue ||
1329 !varDecl.fValue->hasSideEffects())) {
1330 if (varDecl.fValue) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001331 SkASSERT((*iter)->statement()->get() == stmt);
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001332 if (!b.tryRemoveExpressionBefore(iter, varDecl.fValue.get())) {
1333 *outNeedsRescan = true;
Ethan Nicholascb670962017-04-20 19:31:52 -04001334 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001335 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001336 (*iter)->setStatement(std::unique_ptr<Statement>(new Nop()));
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001337 *outUpdated = true;
Ethan Nicholascb670962017-04-20 19:31:52 -04001338 }
1339 break;
1340 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001341 case Statement::Kind::kIf: {
John Stilesa5a97b42020-08-18 11:19:07 -04001342 IfStatement& i = stmt->as<IfStatement>();
Ethan Nicholase6592142020-09-08 10:22:09 -04001343 if (i.fTest->kind() == Expression::Kind::kBoolLiteral) {
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001344 // constant if, collapse down to a single branch
Ethan Nicholas59d660c2020-09-28 09:18:15 -04001345 if (i.fTest->as<BoolLiteral>().value()) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001346 SkASSERT(i.fIfTrue);
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001347 (*iter)->setStatement(std::move(i.fIfTrue));
1348 } else {
1349 if (i.fIfFalse) {
1350 (*iter)->setStatement(std::move(i.fIfFalse));
1351 } else {
1352 (*iter)->setStatement(std::unique_ptr<Statement>(new Nop()));
1353 }
1354 }
1355 *outUpdated = true;
1356 *outNeedsRescan = true;
1357 break;
1358 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001359 if (i.fIfFalse && i.fIfFalse->isEmpty()) {
1360 // else block doesn't do anything, remove it
1361 i.fIfFalse.reset();
1362 *outUpdated = true;
1363 *outNeedsRescan = true;
1364 }
1365 if (!i.fIfFalse && i.fIfTrue->isEmpty()) {
1366 // if block doesn't do anything, no else block
1367 if (i.fTest->hasSideEffects()) {
1368 // test has side effects, keep it
1369 (*iter)->setStatement(std::unique_ptr<Statement>(
1370 new ExpressionStatement(std::move(i.fTest))));
1371 } else {
1372 // no if, no else, no test side effects, kill the whole if
1373 // statement
1374 (*iter)->setStatement(std::unique_ptr<Statement>(new Nop()));
1375 }
1376 *outUpdated = true;
1377 *outNeedsRescan = true;
1378 }
1379 break;
1380 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001381 case Statement::Kind::kSwitch: {
John Stilesa5a97b42020-08-18 11:19:07 -04001382 SwitchStatement& s = stmt->as<SwitchStatement>();
Ethan Nicholas34b19c52020-09-14 11:33:47 -04001383 int64_t switchValue;
1384 if (fIRGenerator->getConstantInt(*s.fValue, &switchValue)) {
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001385 // switch is constant, replace it with the case that matches
1386 bool found = false;
1387 SwitchCase* defaultCase = nullptr;
John Stiles9d944232020-08-19 09:56:49 -04001388 for (const std::unique_ptr<SwitchCase>& c : s.fCases) {
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001389 if (!c->fValue) {
1390 defaultCase = c.get();
1391 continue;
1392 }
Ethan Nicholas34b19c52020-09-14 11:33:47 -04001393 int64_t caseValue;
1394 SkAssertResult(fIRGenerator->getConstantInt(*c->fValue, &caseValue));
1395 if (caseValue == switchValue) {
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001396 std::unique_ptr<Statement> newBlock = block_for_case(&s, c.get());
1397 if (newBlock) {
1398 (*iter)->setStatement(std::move(newBlock));
John Stiles9d944232020-08-19 09:56:49 -04001399 found = true;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001400 break;
1401 } else {
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -04001402 if (s.fIsStatic && !(fFlags & kPermitInvalidStaticTests_Flag)) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001403 this->error(s.fOffset,
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001404 "static switch contains non-static conditional break");
1405 s.fIsStatic = false;
1406 }
1407 return; // can't simplify
1408 }
1409 }
1410 }
1411 if (!found) {
1412 // no matching case. use default if it exists, or kill the whole thing
1413 if (defaultCase) {
1414 std::unique_ptr<Statement> newBlock = block_for_case(&s, defaultCase);
1415 if (newBlock) {
1416 (*iter)->setStatement(std::move(newBlock));
1417 } else {
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -04001418 if (s.fIsStatic && !(fFlags & kPermitInvalidStaticTests_Flag)) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001419 this->error(s.fOffset,
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001420 "static switch contains non-static conditional break");
1421 s.fIsStatic = false;
1422 }
1423 return; // can't simplify
1424 }
1425 } else {
1426 (*iter)->setStatement(std::unique_ptr<Statement>(new Nop()));
1427 }
1428 }
1429 *outUpdated = true;
1430 *outNeedsRescan = true;
1431 }
1432 break;
1433 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001434 case Statement::Kind::kExpression: {
John Stilesa5a97b42020-08-18 11:19:07 -04001435 ExpressionStatement& e = stmt->as<ExpressionStatement>();
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001436 SkASSERT((*iter)->statement()->get() == &e);
Ethan Nicholasd503a5a2020-09-30 09:29:55 -04001437 if (!e.expression()->hasSideEffects()) {
Ethan Nicholascb670962017-04-20 19:31:52 -04001438 // Expression statement with no side effects, kill it
Ethan Nicholasd503a5a2020-09-30 09:29:55 -04001439 if (!b.tryRemoveExpressionBefore(iter, e.expression().get())) {
Ethan Nicholascb670962017-04-20 19:31:52 -04001440 *outNeedsRescan = true;
1441 }
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001442 SkASSERT((*iter)->statement()->get() == stmt);
Ethan Nicholascb670962017-04-20 19:31:52 -04001443 (*iter)->setStatement(std::unique_ptr<Statement>(new Nop()));
1444 *outUpdated = true;
1445 }
1446 break;
1447 }
1448 default:
1449 break;
1450 }
1451}
1452
John Stiles0cc193a2020-09-09 09:39:34 -04001453bool Compiler::scanCFG(FunctionDefinition& f) {
1454 bool madeChanges = false;
1455
Ethan Nicholascb670962017-04-20 19:31:52 -04001456 CFG cfg = CFGGenerator().getCFG(f);
1457 this->computeDataFlow(&cfg);
ethannicholas22f939e2016-10-13 13:25:34 -07001458
1459 // check for unreachable code
1460 for (size_t i = 0; i < cfg.fBlocks.size(); i++) {
John Stiles0cc193a2020-09-09 09:39:34 -04001461 const BasicBlock& block = cfg.fBlocks[i];
John Stiles61e75e32020-10-01 15:42:37 -04001462 if (i != cfg.fStart && !block.fIsReachable && block.fNodes.size()) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001463 int offset;
John Stiles0cc193a2020-09-09 09:39:34 -04001464 const BasicBlock::Node& node = block.fNodes[0];
John Stiles70025e52020-09-28 16:08:58 -04001465 if (node.isStatement()) {
1466 offset = (*node.statement())->fOffset;
1467 } else {
1468 offset = (*node.expression())->fOffset;
1469 if ((*node.expression())->is<BoolLiteral>()) {
1470 // Function inlining can generate do { ... } while(false) loops which always
1471 // break, so the boolean condition is considered unreachable. Since not being
1472 // able to reach a literal is a non-issue in the first place, we don't report an
1473 // error in this case.
1474 continue;
1475 }
Ethan Nicholas86a43402017-01-19 13:32:00 -05001476 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001477 this->error(offset, String("unreachable"));
ethannicholas22f939e2016-10-13 13:25:34 -07001478 }
1479 }
1480 if (fErrorCount) {
John Stiles0cc193a2020-09-09 09:39:34 -04001481 return madeChanges;
ethannicholas22f939e2016-10-13 13:25:34 -07001482 }
1483
Ethan Nicholascb670962017-04-20 19:31:52 -04001484 // check for dead code & undefined variables, perform constant propagation
1485 std::unordered_set<const Variable*> undefinedVariables;
1486 bool updated;
1487 bool needsRescan = false;
1488 do {
1489 if (needsRescan) {
1490 cfg = CFGGenerator().getCFG(f);
1491 this->computeDataFlow(&cfg);
1492 needsRescan = false;
Ethan Nicholas113628d2017-02-02 16:11:39 -05001493 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001494
1495 updated = false;
Ethan Nicholas1de14812020-06-19 15:32:49 -04001496 bool first = true;
Ethan Nicholascb670962017-04-20 19:31:52 -04001497 for (BasicBlock& b : cfg.fBlocks) {
John Stiles61e75e32020-10-01 15:42:37 -04001498 if (!first && !b.fIsReachable) {
Ethan Nicholas1de14812020-06-19 15:32:49 -04001499 // Block was reachable before optimization, but has since become unreachable. In
1500 // addition to being dead code, it's broken - since control flow can't reach it, no
1501 // prior variable definitions can reach it, and therefore variables might look to
Brian Osmanc0213602020-10-06 14:43:32 -04001502 // have not been properly assigned. Kill it by replacing all statements with Nops.
Ethan Nicholas1de14812020-06-19 15:32:49 -04001503 for (BasicBlock::Node& node : b.fNodes) {
John Stiles70025e52020-09-28 16:08:58 -04001504 if (node.isStatement() && !(*node.statement())->is<Nop>()) {
John Stiles0cc193a2020-09-09 09:39:34 -04001505 node.setStatement(std::make_unique<Nop>());
1506 madeChanges = true;
Ethan Nicholas1de14812020-06-19 15:32:49 -04001507 }
1508 }
1509 continue;
1510 }
1511 first = false;
Ethan Nicholascb670962017-04-20 19:31:52 -04001512 DefinitionMap definitions = b.fBefore;
1513
1514 for (auto iter = b.fNodes.begin(); iter != b.fNodes.end() && !needsRescan; ++iter) {
John Stiles70025e52020-09-28 16:08:58 -04001515 if (iter->isExpression()) {
Ethan Nicholascb670962017-04-20 19:31:52 -04001516 this->simplifyExpression(definitions, b, &iter, &undefinedVariables, &updated,
1517 &needsRescan);
1518 } else {
1519 this->simplifyStatement(definitions, b, &iter, &undefinedVariables, &updated,
John Stiles0cc193a2020-09-09 09:39:34 -04001520 &needsRescan);
Ethan Nicholascb670962017-04-20 19:31:52 -04001521 }
Ethan Nicholas4b330df2017-05-17 10:52:55 -04001522 if (needsRescan) {
1523 break;
1524 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001525 this->addDefinitions(*iter, &definitions);
1526 }
Brian Osman01a3eb42020-09-14 11:32:49 -04001527
1528 if (needsRescan) {
1529 break;
1530 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001531 }
John Stiles0cc193a2020-09-09 09:39:34 -04001532 madeChanges |= updated;
Ethan Nicholascb670962017-04-20 19:31:52 -04001533 } while (updated);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001534 SkASSERT(!needsRescan);
ethannicholas22f939e2016-10-13 13:25:34 -07001535
Ethan Nicholas91a10532017-06-22 11:24:38 -04001536 // verify static ifs & switches, clean up dead variable decls
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001537 for (BasicBlock& b : cfg.fBlocks) {
1538 DefinitionMap definitions = b.fBefore;
1539
Ethan Nicholas91a10532017-06-22 11:24:38 -04001540 for (auto iter = b.fNodes.begin(); iter != b.fNodes.end() && !needsRescan;) {
John Stiles70025e52020-09-28 16:08:58 -04001541 if (iter->isStatement()) {
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001542 const Statement& s = **iter->statement();
Ethan Nicholase6592142020-09-08 10:22:09 -04001543 switch (s.kind()) {
1544 case Statement::Kind::kIf:
John Stilesa5a97b42020-08-18 11:19:07 -04001545 if (s.as<IfStatement>().fIsStatic &&
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -04001546 !(fFlags & kPermitInvalidStaticTests_Flag)) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001547 this->error(s.fOffset, "static if has non-static test");
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001548 }
Ethan Nicholas91a10532017-06-22 11:24:38 -04001549 ++iter;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001550 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001551 case Statement::Kind::kSwitch:
John Stilesa5a97b42020-08-18 11:19:07 -04001552 if (s.as<SwitchStatement>().fIsStatic &&
John Stiles0cc193a2020-09-09 09:39:34 -04001553 !(fFlags & kPermitInvalidStaticTests_Flag)) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001554 this->error(s.fOffset, "static switch has non-static test");
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001555 }
Ethan Nicholas91a10532017-06-22 11:24:38 -04001556 ++iter;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001557 break;
1558 default:
Ethan Nicholas91a10532017-06-22 11:24:38 -04001559 ++iter;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001560 break;
1561 }
Ethan Nicholas91a10532017-06-22 11:24:38 -04001562 } else {
1563 ++iter;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001564 }
1565 }
1566 }
1567
ethannicholas22f939e2016-10-13 13:25:34 -07001568 // check for missing return
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001569 if (f.fDeclaration.fReturnType != *fContext->fVoid_Type) {
John Stiles61e75e32020-10-01 15:42:37 -04001570 if (cfg.fBlocks[cfg.fExit].fIsReachable) {
Ethan Nicholase2c49992020-10-05 11:49:11 -04001571 this->error(f.fOffset, String("function '" + String(f.fDeclaration.name()) +
Ethan Nicholasdb80f692019-11-22 14:06:12 -05001572 "' can exit without returning a value"));
ethannicholas22f939e2016-10-13 13:25:34 -07001573 }
1574 }
John Stiles0cc193a2020-09-09 09:39:34 -04001575
1576 return madeChanges;
ethannicholas22f939e2016-10-13 13:25:34 -07001577}
1578
Brian Osman32d53552020-09-23 13:55:20 -04001579std::unique_ptr<Program> Compiler::convertProgram(
1580 Program::Kind kind,
1581 String text,
1582 const Program::Settings& settings,
1583 const std::vector<std::unique_ptr<ExternalValue>>* externalValues) {
1584 SkASSERT(!externalValues || (kind == Program::kGeneric_Kind));
Ethan Nicholas91164d12019-05-15 15:29:54 -04001585
ethannicholasb3058bd2016-07-01 08:22:01 -07001586 fErrorText = "";
1587 fErrorCount = 0;
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001588 fInliner.reset(&fIRGenerator->fContext, fIRGenerator->fModifiers.get(), &settings);
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001589 std::vector<std::unique_ptr<ProgramElement>>* inherited;
ethannicholasd598f792016-07-25 10:08:54 -07001590 std::vector<std::unique_ptr<ProgramElement>> elements;
ethannicholasb3058bd2016-07-01 08:22:01 -07001591 switch (kind) {
1592 case Program::kVertex_Kind:
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001593 inherited = &fVertexInclude;
John Stiles810c8cf2020-08-26 19:46:27 -04001594 fIRGenerator->fIntrinsics = fGPUIntrinsics.get();
Brian Osmane498b3c2020-09-23 14:42:11 -04001595 fIRGenerator->start(&settings, fVertexSymbolTable, inherited);
ethannicholasb3058bd2016-07-01 08:22:01 -07001596 break;
1597 case Program::kFragment_Kind:
Brian Osman00a8b5b2020-10-02 09:06:04 -04001598 inherited = nullptr;
1599 fIRGenerator->fIntrinsics = fFragmentIntrinsics.get();
1600 fIRGenerator->start(&settings, fFragmentSymbolTable, /*inherited=*/nullptr);
ethannicholasb3058bd2016-07-01 08:22:01 -07001601 break;
Ethan Nicholas52cad152017-02-16 16:37:32 -05001602 case Program::kGeometry_Kind:
Ethan Nicholasc18bb512020-07-28 14:46:53 -04001603 this->loadGeometryIntrinsics();
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001604 inherited = &fGeometryInclude;
John Stiles810c8cf2020-08-26 19:46:27 -04001605 fIRGenerator->fIntrinsics = fGPUIntrinsics.get();
Brian Osmane498b3c2020-09-23 14:42:11 -04001606 fIRGenerator->start(&settings, fGeometrySymbolTable, inherited);
Ethan Nicholas52cad152017-02-16 16:37:32 -05001607 break;
Brian Osman8e2ef022020-09-30 13:26:43 -04001608 case Program::kFragmentProcessor_Kind:
1609 this->loadFPIntrinsics();
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001610 inherited = nullptr;
Brian Osman8e2ef022020-09-30 13:26:43 -04001611 fIRGenerator->fIntrinsics = fFPIntrinsics.get();
1612 fIRGenerator->start(&settings, fFPSymbolTable, /*inherited=*/nullptr);
Ethan Nicholas762466e2017-06-29 10:03:38 -04001613 break;
Ethan Nicholas8da1e652019-05-24 11:01:59 -04001614 case Program::kPipelineStage_Kind:
Ethan Nicholasc18bb512020-07-28 14:46:53 -04001615 this->loadPipelineIntrinsics();
Brian Osman8e2ef022020-09-30 13:26:43 -04001616 inherited = nullptr;
1617 fIRGenerator->fIntrinsics = fPipelineIntrinsics.get();
1618 fIRGenerator->start(&settings, fPipelineSymbolTable, /*inherited=*/nullptr);
Ethan Nicholas8da1e652019-05-24 11:01:59 -04001619 break;
Ethan Nicholas746035a2019-04-23 13:31:09 -04001620 case Program::kGeneric_Kind:
Ethan Nicholasc18bb512020-07-28 14:46:53 -04001621 this->loadInterpreterIntrinsics();
Brian Osmaneac49832020-09-18 11:49:22 -04001622 inherited = nullptr;
John Stiles810c8cf2020-08-26 19:46:27 -04001623 fIRGenerator->fIntrinsics = fInterpreterIntrinsics.get();
Brian Osmane498b3c2020-09-23 14:42:11 -04001624 fIRGenerator->start(&settings, fInterpreterSymbolTable, /*inherited=*/nullptr);
Ethan Nicholas0d997662019-04-08 09:46:01 -04001625 break;
ethannicholasb3058bd2016-07-01 08:22:01 -07001626 }
Brian Osman32d53552020-09-23 13:55:20 -04001627 if (externalValues) {
1628 // Add any external values to the symbol table. IRGenerator::start() has pushed a table, so
1629 // we're only making these visible to the current Program.
1630 for (const auto& ev : *externalValues) {
Ethan Nicholase2c49992020-10-05 11:49:11 -04001631 fIRGenerator->fSymbolTable->addWithoutOwnership(ev->name(), ev.get());
Brian Osman32d53552020-09-23 13:55:20 -04001632 }
1633 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001634 std::unique_ptr<String> textPtr(new String(std::move(text)));
1635 fSource = textPtr.get();
Ethan Nicholasc18bb512020-07-28 14:46:53 -04001636 fIRGenerator->convertProgram(kind, textPtr->c_str(), textPtr->size(), &elements);
John Stilesfbd050b2020-08-03 13:21:46 -04001637 auto result = std::make_unique<Program>(kind,
1638 std::move(textPtr),
1639 settings,
1640 fContext,
1641 inherited,
1642 std::move(elements),
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001643 fIRGenerator->releaseModifiers(),
John Stilesfbd050b2020-08-03 13:21:46 -04001644 fIRGenerator->fSymbolTable,
1645 fIRGenerator->fInputs);
Brian Osmane498b3c2020-09-23 14:42:11 -04001646 fIRGenerator->finish();
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001647 if (fErrorCount) {
1648 return nullptr;
1649 }
Ethan Nicholas34b19c52020-09-14 11:33:47 -04001650 if (settings.fOptimize && !this->optimize(*result)) {
1651 return nullptr;
1652 }
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001653 return result;
1654}
1655
Ethan Nicholas00543112018-07-31 09:44:36 -04001656bool Compiler::optimize(Program& program) {
1657 SkASSERT(!fErrorCount);
Ethan Nicholas34b19c52020-09-14 11:33:47 -04001658 fIRGenerator->fKind = program.fKind;
1659 fIRGenerator->fSettings = &program.fSettings;
John Stiles7954d6c2020-09-01 10:53:02 -04001660
Ethan Nicholas34b19c52020-09-14 11:33:47 -04001661 while (fErrorCount == 0) {
1662 bool madeChanges = false;
John Stiles7954d6c2020-09-01 10:53:02 -04001663
Ethan Nicholas34b19c52020-09-14 11:33:47 -04001664 // Scan and optimize based on the control-flow graph for each function.
1665 for (ProgramElement& element : program) {
1666 if (element.is<FunctionDefinition>()) {
1667 madeChanges |= this->scanCFG(element.as<FunctionDefinition>());
1668 }
1669 }
1670
1671 // Perform inline-candidate analysis and inline any functions deemed suitable.
John Stiles881a10c2020-09-19 10:13:24 -04001672 madeChanges |= fInliner.analyze(program);
Ethan Nicholas34b19c52020-09-14 11:33:47 -04001673
1674 // Remove dead functions. We wait until after analysis so that we still report errors,
1675 // even in unused code.
1676 if (program.fSettings.fRemoveDeadFunctions) {
1677 program.fElements.erase(
1678 std::remove_if(program.fElements.begin(),
1679 program.fElements.end(),
1680 [&](const std::unique_ptr<ProgramElement>& element) {
1681 if (!element->is<FunctionDefinition>()) {
1682 return false;
1683 }
1684 const auto& fn = element->as<FunctionDefinition>();
1685 bool dead = fn.fDeclaration.fCallCount == 0 &&
Ethan Nicholase2c49992020-10-05 11:49:11 -04001686 fn.fDeclaration.name() != "main";
Ethan Nicholas34b19c52020-09-14 11:33:47 -04001687 madeChanges |= dead;
1688 return dead;
1689 }),
1690 program.fElements.end());
1691 }
1692
1693 if (program.fKind != Program::kFragmentProcessor_Kind) {
Brian Osmanc0213602020-10-06 14:43:32 -04001694 // Remove declarations of dead global variables
Ethan Nicholas34b19c52020-09-14 11:33:47 -04001695 program.fElements.erase(
1696 std::remove_if(program.fElements.begin(), program.fElements.end(),
1697 [&](const std::unique_ptr<ProgramElement>& element) {
Brian Osmanc0213602020-10-06 14:43:32 -04001698 if (!element->is<GlobalVarDeclaration>()) {
Ethan Nicholas34b19c52020-09-14 11:33:47 -04001699 return false;
1700 }
Brian Osmanc0213602020-10-06 14:43:32 -04001701 const auto& varDecl = element->as<GlobalVarDeclaration>();
1702 bool dead = varDecl.fDecl->fVar->dead();
Ethan Nicholas34b19c52020-09-14 11:33:47 -04001703 madeChanges |= dead;
1704 return dead;
1705 }),
1706 program.fElements.end());
1707 }
John Stiles73a6bff2020-09-09 13:40:37 -04001708
Ethan Nicholas34b19c52020-09-14 11:33:47 -04001709 if (!madeChanges) {
1710 break;
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001711 }
Ethan Nicholas00543112018-07-31 09:44:36 -04001712 }
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001713 program.finish();
Ethan Nicholas00543112018-07-31 09:44:36 -04001714 return fErrorCount == 0;
1715}
1716
Brian Osmanfb32ddf2019-06-18 10:14:20 -04001717#if defined(SKSL_STANDALONE) || SK_SUPPORT_GPU
1718
Ethan Nicholas00543112018-07-31 09:44:36 -04001719bool Compiler::toSPIRV(Program& program, OutputStream& out) {
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001720#ifdef SK_ENABLE_SPIRV_VALIDATION
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001721 StringStream buffer;
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001722 fSource = program.fSource.get();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001723 SPIRVCodeGenerator cg(&fIRGenerator->fContext, fIRGenerator->fModifiers.get(), &program, this,
1724 &buffer);
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001725 bool result = cg.generateCode();
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001726 fSource = nullptr;
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001727 if (result) {
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001728 spvtools::SpirvTools tools(SPV_ENV_VULKAN_1_0);
Ethan Nicholas762466e2017-06-29 10:03:38 -04001729 const String& data = buffer.str();
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001730 SkASSERT(0 == data.size() % 4);
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001731 auto dumpmsg = [](spv_message_level_t, const char*, const spv_position_t&, const char* m) {
1732 SkDebugf("SPIR-V validation error: %s\n", m);
1733 };
1734 tools.SetMessageConsumer(dumpmsg);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001735 // Verify that the SPIR-V we produced is valid. If this SkASSERT fails, check the logs prior
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001736 // to the failure to see the validation errors.
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001737 SkAssertResult(tools.Validate((const uint32_t*) data.c_str(), data.size() / 4));
Ethan Nicholas762466e2017-06-29 10:03:38 -04001738 out.write(data.c_str(), data.size());
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001739 }
1740#else
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001741 fSource = program.fSource.get();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001742 SPIRVCodeGenerator cg(&fIRGenerator->fContext, fIRGenerator->fModifiers.get(), &program, this,
1743 &out);
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001744 bool result = cg.generateCode();
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001745 fSource = nullptr;
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001746#endif
Ethan Nicholasce33f102016-12-09 17:22:59 -05001747 return result;
1748}
1749
Ethan Nicholas00543112018-07-31 09:44:36 -04001750bool Compiler::toSPIRV(Program& program, String* out) {
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001751 StringStream buffer;
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001752 bool result = this->toSPIRV(program, buffer);
1753 if (result) {
Ethan Nicholas762466e2017-06-29 10:03:38 -04001754 *out = buffer.str();
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001755 }
1756 return result;
1757}
1758
Ethan Nicholas00543112018-07-31 09:44:36 -04001759bool Compiler::toGLSL(Program& program, OutputStream& out) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001760 fSource = program.fSource.get();
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001761 GLSLCodeGenerator cg(fContext.get(), &program, this, &out);
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001762 bool result = cg.generateCode();
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001763 fSource = nullptr;
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001764 return result;
1765}
1766
Ethan Nicholas00543112018-07-31 09:44:36 -04001767bool Compiler::toGLSL(Program& program, String* out) {
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001768 StringStream buffer;
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001769 bool result = this->toGLSL(program, buffer);
1770 if (result) {
Ethan Nicholas762466e2017-06-29 10:03:38 -04001771 *out = buffer.str();
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001772 }
1773 return result;
1774}
1775
Brian Osmanc0243912020-02-19 15:35:26 -05001776bool Compiler::toHLSL(Program& program, String* out) {
1777 String spirv;
1778 if (!this->toSPIRV(program, &spirv)) {
1779 return false;
1780 }
1781
1782 return SPIRVtoHLSL(spirv, out);
1783}
1784
Ethan Nicholas00543112018-07-31 09:44:36 -04001785bool Compiler::toMetal(Program& program, OutputStream& out) {
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001786 MetalCodeGenerator cg(fContext.get(), &program, this, &out);
Ethan Nicholascc305772017-10-13 16:17:45 -04001787 bool result = cg.generateCode();
Ethan Nicholascc305772017-10-13 16:17:45 -04001788 return result;
1789}
1790
Ethan Nicholas00543112018-07-31 09:44:36 -04001791bool Compiler::toMetal(Program& program, String* out) {
Timothy Liangb8eeb802018-07-23 16:46:16 -04001792 StringStream buffer;
1793 bool result = this->toMetal(program, buffer);
1794 if (result) {
1795 *out = buffer.str();
1796 }
1797 return result;
1798}
1799
Greg Daniela28ea672020-09-25 11:12:56 -04001800#if defined(SKSL_STANDALONE) || GR_TEST_UTILS
Ethan Nicholas00543112018-07-31 09:44:36 -04001801bool Compiler::toCPP(Program& program, String name, OutputStream& out) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001802 fSource = program.fSource.get();
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001803 CPPCodeGenerator cg(fContext.get(), &program, this, name, &out);
Ethan Nicholas762466e2017-06-29 10:03:38 -04001804 bool result = cg.generateCode();
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001805 fSource = nullptr;
Ethan Nicholas762466e2017-06-29 10:03:38 -04001806 return result;
1807}
1808
Ethan Nicholas00543112018-07-31 09:44:36 -04001809bool Compiler::toH(Program& program, String name, OutputStream& out) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001810 fSource = program.fSource.get();
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001811 HCodeGenerator cg(fContext.get(), &program, this, name, &out);
Ethan Nicholas762466e2017-06-29 10:03:38 -04001812 bool result = cg.generateCode();
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001813 fSource = nullptr;
Ethan Nicholas00543112018-07-31 09:44:36 -04001814 return result;
1815}
Greg Daniela28ea672020-09-25 11:12:56 -04001816#endif // defined(SKSL_STANDALONE) || GR_TEST_UTILS
Ethan Nicholas00543112018-07-31 09:44:36 -04001817
Ethan Nicholas2a479a52020-08-18 16:29:45 -04001818#endif // defined(SKSL_STANDALONE) || SK_SUPPORT_GPU
Brian Osman2e29ab52019-09-20 12:19:11 -04001819
1820#if !defined(SKSL_STANDALONE) && SK_SUPPORT_GPU
Brian Osmana4b91692020-08-10 14:26:16 -04001821bool Compiler::toPipelineStage(Program& program, PipelineStageArgs* outArgs) {
Ethan Nicholas00543112018-07-31 09:44:36 -04001822 fSource = program.fSource.get();
1823 StringStream buffer;
Brian Osman300fe1d2020-01-23 15:42:43 -05001824 PipelineStageCodeGenerator cg(fContext.get(), &program, this, &buffer, outArgs);
Ethan Nicholas00543112018-07-31 09:44:36 -04001825 bool result = cg.generateCode();
1826 fSource = nullptr;
1827 if (result) {
Brian Osman107c6662019-12-30 15:02:30 -05001828 outArgs->fCode = buffer.str();
Ethan Nicholas00543112018-07-31 09:44:36 -04001829 }
Ethan Nicholas762466e2017-06-29 10:03:38 -04001830 return result;
1831}
Brian Osmanfb32ddf2019-06-18 10:14:20 -04001832#endif
1833
Ethan Nicholas0e9401d2019-03-21 11:05:37 -04001834std::unique_ptr<ByteCode> Compiler::toByteCode(Program& program) {
Mike Klein853d4ed2020-08-20 00:41:00 +00001835#if defined(SK_ENABLE_SKSL_INTERPRETER)
Brian Osman808f0212020-01-21 15:36:47 -05001836 fSource = program.fSource.get();
Ethan Nicholas0e9401d2019-03-21 11:05:37 -04001837 std::unique_ptr<ByteCode> result(new ByteCode());
Brian Osmanb08cc022020-04-02 11:38:40 -04001838 ByteCodeGenerator cg(fContext.get(), &program, this, result.get());
1839 bool success = cg.generateCode();
1840 fSource = nullptr;
1841 if (success) {
Ethan Nicholas0e9401d2019-03-21 11:05:37 -04001842 return result;
1843 }
Mike Klein853d4ed2020-08-20 00:41:00 +00001844#else
1845 ABORT("ByteCode interpreter not enabled");
1846#endif
Ethan Nicholas0e9401d2019-03-21 11:05:37 -04001847 return nullptr;
1848}
1849
Brian Osman401a0092020-09-10 14:47:24 -04001850const char* Compiler::OperatorName(Token::Kind op) {
1851 switch (op) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001852 case Token::Kind::TK_PLUS: return "+";
1853 case Token::Kind::TK_MINUS: return "-";
1854 case Token::Kind::TK_STAR: return "*";
1855 case Token::Kind::TK_SLASH: return "/";
1856 case Token::Kind::TK_PERCENT: return "%";
1857 case Token::Kind::TK_SHL: return "<<";
1858 case Token::Kind::TK_SHR: return ">>";
1859 case Token::Kind::TK_LOGICALNOT: return "!";
1860 case Token::Kind::TK_LOGICALAND: return "&&";
1861 case Token::Kind::TK_LOGICALOR: return "||";
1862 case Token::Kind::TK_LOGICALXOR: return "^^";
1863 case Token::Kind::TK_BITWISENOT: return "~";
1864 case Token::Kind::TK_BITWISEAND: return "&";
1865 case Token::Kind::TK_BITWISEOR: return "|";
1866 case Token::Kind::TK_BITWISEXOR: return "^";
1867 case Token::Kind::TK_EQ: return "=";
1868 case Token::Kind::TK_EQEQ: return "==";
1869 case Token::Kind::TK_NEQ: return "!=";
1870 case Token::Kind::TK_LT: return "<";
1871 case Token::Kind::TK_GT: return ">";
1872 case Token::Kind::TK_LTEQ: return "<=";
1873 case Token::Kind::TK_GTEQ: return ">=";
1874 case Token::Kind::TK_PLUSEQ: return "+=";
1875 case Token::Kind::TK_MINUSEQ: return "-=";
1876 case Token::Kind::TK_STAREQ: return "*=";
1877 case Token::Kind::TK_SLASHEQ: return "/=";
1878 case Token::Kind::TK_PERCENTEQ: return "%=";
1879 case Token::Kind::TK_SHLEQ: return "<<=";
1880 case Token::Kind::TK_SHREQ: return ">>=";
1881 case Token::Kind::TK_LOGICALANDEQ: return "&&=";
1882 case Token::Kind::TK_LOGICALOREQ: return "||=";
1883 case Token::Kind::TK_LOGICALXOREQ: return "^^=";
1884 case Token::Kind::TK_BITWISEANDEQ: return "&=";
1885 case Token::Kind::TK_BITWISEOREQ: return "|=";
1886 case Token::Kind::TK_BITWISEXOREQ: return "^=";
1887 case Token::Kind::TK_PLUSPLUS: return "++";
1888 case Token::Kind::TK_MINUSMINUS: return "--";
1889 case Token::Kind::TK_COMMA: return ",";
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001890 default:
Brian Osman401a0092020-09-10 14:47:24 -04001891 ABORT("unsupported operator: %d\n", (int) op);
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001892 }
1893}
1894
1895
1896bool Compiler::IsAssignment(Token::Kind op) {
1897 switch (op) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001898 case Token::Kind::TK_EQ: // fall through
1899 case Token::Kind::TK_PLUSEQ: // fall through
1900 case Token::Kind::TK_MINUSEQ: // fall through
1901 case Token::Kind::TK_STAREQ: // fall through
1902 case Token::Kind::TK_SLASHEQ: // fall through
1903 case Token::Kind::TK_PERCENTEQ: // fall through
1904 case Token::Kind::TK_SHLEQ: // fall through
1905 case Token::Kind::TK_SHREQ: // fall through
1906 case Token::Kind::TK_BITWISEOREQ: // fall through
1907 case Token::Kind::TK_BITWISEXOREQ: // fall through
1908 case Token::Kind::TK_BITWISEANDEQ: // fall through
1909 case Token::Kind::TK_LOGICALOREQ: // fall through
1910 case Token::Kind::TK_LOGICALXOREQ: // fall through
1911 case Token::Kind::TK_LOGICALANDEQ:
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001912 return true;
1913 default:
1914 return false;
1915 }
1916}
1917
Brian Osman401a0092020-09-10 14:47:24 -04001918Token::Kind Compiler::RemoveAssignment(Token::Kind op) {
1919 switch (op) {
1920 case Token::Kind::TK_PLUSEQ: return Token::Kind::TK_PLUS;
1921 case Token::Kind::TK_MINUSEQ: return Token::Kind::TK_MINUS;
1922 case Token::Kind::TK_STAREQ: return Token::Kind::TK_STAR;
1923 case Token::Kind::TK_SLASHEQ: return Token::Kind::TK_SLASH;
1924 case Token::Kind::TK_PERCENTEQ: return Token::Kind::TK_PERCENT;
1925 case Token::Kind::TK_SHLEQ: return Token::Kind::TK_SHL;
1926 case Token::Kind::TK_SHREQ: return Token::Kind::TK_SHR;
1927 case Token::Kind::TK_BITWISEOREQ: return Token::Kind::TK_BITWISEOR;
1928 case Token::Kind::TK_BITWISEXOREQ: return Token::Kind::TK_BITWISEXOR;
1929 case Token::Kind::TK_BITWISEANDEQ: return Token::Kind::TK_BITWISEAND;
1930 case Token::Kind::TK_LOGICALOREQ: return Token::Kind::TK_LOGICALOR;
1931 case Token::Kind::TK_LOGICALXOREQ: return Token::Kind::TK_LOGICALXOR;
1932 case Token::Kind::TK_LOGICALANDEQ: return Token::Kind::TK_LOGICALAND;
1933 default: return op;
1934 }
1935}
1936
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001937Position Compiler::position(int offset) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001938 SkASSERT(fSource);
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001939 int line = 1;
1940 int column = 1;
1941 for (int i = 0; i < offset; i++) {
1942 if ((*fSource)[i] == '\n') {
1943 ++line;
1944 column = 1;
1945 }
1946 else {
1947 ++column;
1948 }
1949 }
1950 return Position(line, column);
1951}
1952
1953void Compiler::error(int offset, String msg) {
ethannicholasb3058bd2016-07-01 08:22:01 -07001954 fErrorCount++;
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001955 Position pos = this->position(offset);
1956 fErrorText += "error: " + to_string(pos.fLine) + ": " + msg.c_str() + "\n";
ethannicholasb3058bd2016-07-01 08:22:01 -07001957}
1958
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001959String Compiler::errorText() {
Ethan Nicholas00543112018-07-31 09:44:36 -04001960 this->writeErrorCount();
1961 fErrorCount = 0;
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001962 String result = fErrorText;
ethannicholasb3058bd2016-07-01 08:22:01 -07001963 return result;
1964}
1965
1966void Compiler::writeErrorCount() {
1967 if (fErrorCount) {
1968 fErrorText += to_string(fErrorCount) + " error";
1969 if (fErrorCount > 1) {
1970 fErrorText += "s";
1971 }
1972 fErrorText += "\n";
1973 }
1974}
1975
John Stilesa6841be2020-08-06 14:11:56 -04001976} // namespace SkSL