blob: adbf37435e7beba7c3a730719460101b301d7a06 [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);
John Stilesb8cc6652020-10-08 09:12:07 -0400123 #define ADD_TYPE(t) fRootSymbolTable->addWithoutOwnership(fContext->f ## t ## _Type.get())
ethannicholasb3058bd2016-07-01 08:22:01 -0700124 ADD_TYPE(Void);
125 ADD_TYPE(Float);
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400126 ADD_TYPE(Float2);
127 ADD_TYPE(Float3);
128 ADD_TYPE(Float4);
Ethan Nicholasdcba08e2017-08-02 10:52:54 -0400129 ADD_TYPE(Half);
130 ADD_TYPE(Half2);
131 ADD_TYPE(Half3);
132 ADD_TYPE(Half4);
ethannicholasb3058bd2016-07-01 08:22:01 -0700133 ADD_TYPE(Int);
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400134 ADD_TYPE(Int2);
135 ADD_TYPE(Int3);
136 ADD_TYPE(Int4);
ethannicholasb3058bd2016-07-01 08:22:01 -0700137 ADD_TYPE(UInt);
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400138 ADD_TYPE(UInt2);
139 ADD_TYPE(UInt3);
140 ADD_TYPE(UInt4);
Ethan Nicholasdcba08e2017-08-02 10:52:54 -0400141 ADD_TYPE(Short);
142 ADD_TYPE(Short2);
143 ADD_TYPE(Short3);
144 ADD_TYPE(Short4);
145 ADD_TYPE(UShort);
146 ADD_TYPE(UShort2);
147 ADD_TYPE(UShort3);
148 ADD_TYPE(UShort4);
Ruiqi Maob609e6d2018-07-17 10:19:38 -0400149 ADD_TYPE(Byte);
150 ADD_TYPE(Byte2);
151 ADD_TYPE(Byte3);
152 ADD_TYPE(Byte4);
153 ADD_TYPE(UByte);
154 ADD_TYPE(UByte2);
155 ADD_TYPE(UByte3);
156 ADD_TYPE(UByte4);
ethannicholasb3058bd2016-07-01 08:22:01 -0700157 ADD_TYPE(Bool);
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400158 ADD_TYPE(Bool2);
159 ADD_TYPE(Bool3);
160 ADD_TYPE(Bool4);
161 ADD_TYPE(Float2x2);
162 ADD_TYPE(Float2x3);
163 ADD_TYPE(Float2x4);
164 ADD_TYPE(Float3x2);
165 ADD_TYPE(Float3x3);
166 ADD_TYPE(Float3x4);
167 ADD_TYPE(Float4x2);
168 ADD_TYPE(Float4x3);
169 ADD_TYPE(Float4x4);
Ethan Nicholasdcba08e2017-08-02 10:52:54 -0400170 ADD_TYPE(Half2x2);
171 ADD_TYPE(Half2x3);
172 ADD_TYPE(Half2x4);
173 ADD_TYPE(Half3x2);
174 ADD_TYPE(Half3x3);
175 ADD_TYPE(Half3x4);
176 ADD_TYPE(Half4x2);
177 ADD_TYPE(Half4x3);
178 ADD_TYPE(Half4x4);
ethannicholasb3058bd2016-07-01 08:22:01 -0700179 ADD_TYPE(GenType);
Ethan Nicholasdcba08e2017-08-02 10:52:54 -0400180 ADD_TYPE(GenHType);
ethannicholasb3058bd2016-07-01 08:22:01 -0700181 ADD_TYPE(GenIType);
182 ADD_TYPE(GenUType);
183 ADD_TYPE(GenBType);
184 ADD_TYPE(Mat);
185 ADD_TYPE(Vec);
186 ADD_TYPE(GVec);
187 ADD_TYPE(GVec2);
188 ADD_TYPE(GVec3);
189 ADD_TYPE(GVec4);
Ethan Nicholasdcba08e2017-08-02 10:52:54 -0400190 ADD_TYPE(HVec);
ethannicholasb3058bd2016-07-01 08:22:01 -0700191 ADD_TYPE(IVec);
192 ADD_TYPE(UVec);
Ethan Nicholasdcba08e2017-08-02 10:52:54 -0400193 ADD_TYPE(SVec);
194 ADD_TYPE(USVec);
Ruiqi Maob609e6d2018-07-17 10:19:38 -0400195 ADD_TYPE(ByteVec);
196 ADD_TYPE(UByteVec);
ethannicholasb3058bd2016-07-01 08:22:01 -0700197 ADD_TYPE(BVec);
198
199 ADD_TYPE(Sampler1D);
200 ADD_TYPE(Sampler2D);
201 ADD_TYPE(Sampler3D);
ethannicholas5961bc92016-10-12 06:39:56 -0700202 ADD_TYPE(SamplerExternalOES);
ethannicholasb3058bd2016-07-01 08:22:01 -0700203 ADD_TYPE(SamplerCube);
204 ADD_TYPE(Sampler2DRect);
205 ADD_TYPE(Sampler1DArray);
206 ADD_TYPE(Sampler2DArray);
207 ADD_TYPE(SamplerCubeArray);
208 ADD_TYPE(SamplerBuffer);
209 ADD_TYPE(Sampler2DMS);
210 ADD_TYPE(Sampler2DMSArray);
211
Brian Salomonbf7b6202016-11-11 16:08:03 -0500212 ADD_TYPE(ISampler2D);
213
Brian Salomon2a51de82016-11-16 12:06:01 -0500214 ADD_TYPE(Image2D);
215 ADD_TYPE(IImage2D);
216
Greg Daniel64773e62016-11-22 09:44:03 -0500217 ADD_TYPE(SubpassInput);
218 ADD_TYPE(SubpassInputMS);
219
ethannicholasb3058bd2016-07-01 08:22:01 -0700220 ADD_TYPE(GSampler1D);
221 ADD_TYPE(GSampler2D);
222 ADD_TYPE(GSampler3D);
223 ADD_TYPE(GSamplerCube);
224 ADD_TYPE(GSampler2DRect);
225 ADD_TYPE(GSampler1DArray);
226 ADD_TYPE(GSampler2DArray);
227 ADD_TYPE(GSamplerCubeArray);
228 ADD_TYPE(GSamplerBuffer);
229 ADD_TYPE(GSampler2DMS);
230 ADD_TYPE(GSampler2DMSArray);
231
232 ADD_TYPE(Sampler1DShadow);
233 ADD_TYPE(Sampler2DShadow);
234 ADD_TYPE(SamplerCubeShadow);
235 ADD_TYPE(Sampler2DRectShadow);
236 ADD_TYPE(Sampler1DArrayShadow);
237 ADD_TYPE(Sampler2DArrayShadow);
238 ADD_TYPE(SamplerCubeArrayShadow);
239 ADD_TYPE(GSampler2DArrayShadow);
240 ADD_TYPE(GSamplerCubeArrayShadow);
Ethan Nicholasc9472af2017-10-10 16:30:21 -0400241 ADD_TYPE(FragmentProcessor);
Stephen Whiteff5d7a22019-07-26 17:42:06 -0400242 ADD_TYPE(Sampler);
243 ADD_TYPE(Texture2D);
ethannicholasb3058bd2016-07-01 08:22:01 -0700244
Brian Osman28590d52020-03-23 16:59:08 -0400245 StringFragment fpAliasName("shader");
John Stiles49a547f2020-10-06 16:14:37 -0400246 fRootSymbolTable->addAlias(fpAliasName, fContext->fFragmentProcessor_Type.get());
Brian Osman28590d52020-03-23 16:59:08 -0400247
Brian Osman3887a012020-09-30 13:22:27 -0400248 // sk_Caps is "builtin", but all references to it are resolved to Settings, so we don't need to
249 // treat it as builtin (ie, no need to clone it into the Program).
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700250 StringFragment skCapsName("sk_Caps");
John Stilesb8cc6652020-10-08 09:12:07 -0400251 fRootSymbolTable->add(std::make_unique<Variable>(/*offset=*/-1,
Ethan Nicholas041fd0a2020-10-07 16:42:04 -0400252 fIRGenerator->fModifiers->handle(Modifiers()),
253 skCapsName, fContext->fSkCaps_Type.get(),
Brian Osman3887a012020-09-30 13:22:27 -0400254 /*builtin=*/false, Variable::kGlobal_Storage));
Ethan Nicholas3605ace2016-11-21 15:59:48 -0500255
Brian Osman00a8b5b2020-10-02 09:06:04 -0400256 fIRGenerator->fIntrinsics = nullptr;
257 std::vector<std::unique_ptr<ProgramElement>> gpuElements;
258 std::vector<std::unique_ptr<ProgramElement>> fragElements;
Brian Osmandd496172020-08-08 08:17:18 -0400259#if SKSL_STANDALONE
Brian Osmaneac49832020-09-18 11:49:22 -0400260 this->processIncludeFile(Program::kFragment_Kind, SKSL_GPU_INCLUDE, fRootSymbolTable,
Brian Osman00a8b5b2020-10-02 09:06:04 -0400261 &gpuElements, &fGpuSymbolTable);
Ethan Nicholasb33fa3f2020-08-06 13:00:19 -0400262 this->processIncludeFile(Program::kVertex_Kind, SKSL_VERT_INCLUDE, fGpuSymbolTable,
263 &fVertexInclude, &fVertexSymbolTable);
264 this->processIncludeFile(Program::kFragment_Kind, SKSL_FRAG_INCLUDE, fGpuSymbolTable,
Brian Osman00a8b5b2020-10-02 09:06:04 -0400265 &fragElements, &fFragmentSymbolTable);
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400266#else
267 {
Ethan Nicholas041fd0a2020-10-07 16:42:04 -0400268 Rehydrator rehydrator(&fIRGenerator->fContext, fIRGenerator->fModifiers.get(),
269 fRootSymbolTable, this, SKSL_INCLUDE_sksl_gpu,
Brian Osmaneac49832020-09-18 11:49:22 -0400270 SKSL_INCLUDE_sksl_gpu_LENGTH);
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400271 fGpuSymbolTable = rehydrator.symbolTable();
Brian Osman00a8b5b2020-10-02 09:06:04 -0400272 gpuElements = rehydrator.elements();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -0400273 fModifiers.push_back(fIRGenerator->releaseModifiers());
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400274 }
275 {
Ethan Nicholas041fd0a2020-10-07 16:42:04 -0400276 Rehydrator rehydrator(&fIRGenerator->fContext, fIRGenerator->fModifiers.get(),
277 fGpuSymbolTable, this, SKSL_INCLUDE_sksl_vert,
Brian Osmaneac49832020-09-18 11:49:22 -0400278 SKSL_INCLUDE_sksl_vert_LENGTH);
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400279 fVertexSymbolTable = rehydrator.symbolTable();
280 fVertexInclude = rehydrator.elements();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -0400281 fModifiers.push_back(fIRGenerator->releaseModifiers());
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400282 }
283 {
Ethan Nicholas041fd0a2020-10-07 16:42:04 -0400284 Rehydrator rehydrator(&fIRGenerator->fContext, fIRGenerator->fModifiers.get(),
285 fGpuSymbolTable, this, SKSL_INCLUDE_sksl_frag,
Brian Osmaneac49832020-09-18 11:49:22 -0400286 SKSL_INCLUDE_sksl_frag_LENGTH);
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400287 fFragmentSymbolTable = rehydrator.symbolTable();
Brian Osman00a8b5b2020-10-02 09:06:04 -0400288 fragElements = rehydrator.elements();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -0400289 fModifiers.push_back(fIRGenerator->releaseModifiers());
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400290 }
291#endif
John Stilesbc0c29e2020-09-28 13:13:40 -0400292 // Call counts are used to track dead-stripping and inlinability within the program being
293 // currently compiled, and always should start at zero for a new program. Zero out any call
294 // counts that were registered during the assembly of the intrinsics/include data. (If we
295 // actually use calls from inside the intrinsics, we will clone them into the program and they
296 // will get new call counts.)
Brian Osman00a8b5b2020-10-02 09:06:04 -0400297 reset_call_counts(&gpuElements);
John Stilesbc0c29e2020-09-28 13:13:40 -0400298 reset_call_counts(&fVertexInclude);
Brian Osman00a8b5b2020-10-02 09:06:04 -0400299 reset_call_counts(&fragElements);
John Stilesbc0c29e2020-09-28 13:13:40 -0400300
Brian Osman00a8b5b2020-10-02 09:06:04 -0400301 fGPUIntrinsics = std::make_unique<IRIntrinsicMap>(/*parent=*/nullptr);
302 grab_intrinsics(&gpuElements, fGPUIntrinsics.get());
303
304 fFragmentIntrinsics = std::make_unique<IRIntrinsicMap>(fGPUIntrinsics.get());
305 grab_intrinsics(&fragElements, fFragmentIntrinsics.get());
ethannicholasb3058bd2016-07-01 08:22:01 -0700306}
307
John Stiles656427a2020-08-27 15:26:26 -0400308Compiler::~Compiler() {}
ethannicholasb3058bd2016-07-01 08:22:01 -0700309
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400310void Compiler::loadGeometryIntrinsics() {
311 if (fGeometrySymbolTable) {
312 return;
313 }
Brian Osmandd496172020-08-08 08:17:18 -0400314 #if !SKSL_STANDALONE
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400315 {
Ethan Nicholas041fd0a2020-10-07 16:42:04 -0400316 Rehydrator rehydrator(&fIRGenerator->fContext, fIRGenerator->fModifiers.get(),
317 fGpuSymbolTable, this, SKSL_INCLUDE_sksl_geom,
318 SKSL_INCLUDE_sksl_geom_LENGTH);
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400319 fGeometrySymbolTable = rehydrator.symbolTable();
320 fGeometryInclude = rehydrator.elements();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -0400321 fModifiers.push_back(fIRGenerator->releaseModifiers());
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400322 }
323 #else
Ethan Nicholasb33fa3f2020-08-06 13:00:19 -0400324 this->processIncludeFile(Program::kGeometry_Kind, SKSL_GEOM_INCLUDE, fGpuSymbolTable,
325 &fGeometryInclude, &fGeometrySymbolTable);
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400326 #endif
327}
328
Brian Osman8e2ef022020-09-30 13:26:43 -0400329void Compiler::loadFPIntrinsics() {
330 if (fFPSymbolTable) {
331 return;
332 }
333 fFPIntrinsics = std::make_unique<IRIntrinsicMap>(fGPUIntrinsics.get());
334 std::vector<std::unique_ptr<ProgramElement>> fpElements;
335 #if !SKSL_STANDALONE
336 {
Ethan Nicholas041fd0a2020-10-07 16:42:04 -0400337 Rehydrator rehydrator(&fIRGenerator->fContext, fIRGenerator->fModifiers.get(),
338 fGpuSymbolTable, this, SKSL_INCLUDE_sksl_fp,
Brian Osman8e2ef022020-09-30 13:26:43 -0400339 SKSL_INCLUDE_sksl_fp_LENGTH);
340 fFPSymbolTable = rehydrator.symbolTable();
341 fpElements = rehydrator.elements();
342 }
343 #else
344 this->processIncludeFile(Program::kFragmentProcessor_Kind, SKSL_FP_INCLUDE, fGpuSymbolTable,
345 &fpElements, &fFPSymbolTable);
346 #endif
347 grab_intrinsics(&fpElements, fFPIntrinsics.get());
Brian Osman8e2ef022020-09-30 13:26:43 -0400348}
349
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400350void Compiler::loadPipelineIntrinsics() {
351 if (fPipelineSymbolTable) {
352 return;
353 }
Brian Osman00a8b5b2020-10-02 09:06:04 -0400354 fPipelineIntrinsics = std::make_unique<IRIntrinsicMap>(fGPUIntrinsics.get());
Brian Osman8e2ef022020-09-30 13:26:43 -0400355 std::vector<std::unique_ptr<ProgramElement>> pipelineIntrinics;
Brian Osmandd496172020-08-08 08:17:18 -0400356 #if !SKSL_STANDALONE
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400357 {
Ethan Nicholas041fd0a2020-10-07 16:42:04 -0400358 Rehydrator rehydrator(&fIRGenerator->fContext, fIRGenerator->fModifiers.get(),
359 fGpuSymbolTable, this, SKSL_INCLUDE_sksl_pipeline,
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400360 SKSL_INCLUDE_sksl_pipeline_LENGTH);
361 fPipelineSymbolTable = rehydrator.symbolTable();
Brian Osman8e2ef022020-09-30 13:26:43 -0400362 pipelineIntrinics = rehydrator.elements();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -0400363 fModifiers.push_back(fIRGenerator->releaseModifiers());
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400364 }
365 #else
366 this->processIncludeFile(Program::kPipelineStage_Kind, SKSL_PIPELINE_INCLUDE,
Brian Osman8e2ef022020-09-30 13:26:43 -0400367 fGpuSymbolTable, &pipelineIntrinics, &fPipelineSymbolTable);
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400368 #endif
Brian Osman8e2ef022020-09-30 13:26:43 -0400369 grab_intrinsics(&pipelineIntrinics, fPipelineIntrinsics.get());
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400370}
371
372void Compiler::loadInterpreterIntrinsics() {
373 if (fInterpreterSymbolTable) {
374 return;
375 }
Brian Osman00a8b5b2020-10-02 09:06:04 -0400376 fInterpreterIntrinsics = std::make_unique<IRIntrinsicMap>(/*parent=*/nullptr);
377 std::vector<std::unique_ptr<ProgramElement>> interpElements;
Brian Osmandd496172020-08-08 08:17:18 -0400378 #if !SKSL_STANDALONE
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400379 {
Ethan Nicholas041fd0a2020-10-07 16:42:04 -0400380 Rehydrator rehydrator(&fIRGenerator->fContext, fIRGenerator->fModifiers.get(),
381 fRootSymbolTable, this, SKSL_INCLUDE_sksl_interp,
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400382 SKSL_INCLUDE_sksl_interp_LENGTH);
383 fInterpreterSymbolTable = rehydrator.symbolTable();
Brian Osman00a8b5b2020-10-02 09:06:04 -0400384 interpElements = rehydrator.elements();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -0400385 fModifiers.push_back(fIRGenerator->releaseModifiers());
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400386 }
387 #else
388 this->processIncludeFile(Program::kGeneric_Kind, SKSL_INTERP_INCLUDE,
Brian Osman00a8b5b2020-10-02 09:06:04 -0400389 fIRGenerator->fSymbolTable, &interpElements,
Ethan Nicholasb33fa3f2020-08-06 13:00:19 -0400390 &fInterpreterSymbolTable);
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400391 #endif
Brian Osman00a8b5b2020-10-02 09:06:04 -0400392 grab_intrinsics(&interpElements, fInterpreterIntrinsics.get());
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400393}
394
Ethan Nicholasb33fa3f2020-08-06 13:00:19 -0400395void Compiler::processIncludeFile(Program::Kind kind, const char* path,
Ethan Nicholas8da1e652019-05-24 11:01:59 -0400396 std::shared_ptr<SymbolTable> base,
397 std::vector<std::unique_ptr<ProgramElement>>* outElements,
398 std::shared_ptr<SymbolTable>* outSymbolTable) {
Ethan Nicholasb33fa3f2020-08-06 13:00:19 -0400399 std::ifstream in(path);
Brian Osmane498b3c2020-09-23 14:42:11 -0400400 std::unique_ptr<String> text = std::make_unique<String>(std::istreambuf_iterator<char>(in),
401 std::istreambuf_iterator<char>());
Ethan Nicholasb33fa3f2020-08-06 13:00:19 -0400402 if (in.rdstate()) {
403 printf("error reading %s\n", path);
404 abort();
405 }
Brian Osmane498b3c2020-09-23 14:42:11 -0400406 const String* source = fRootSymbolTable->takeOwnershipOfString(std::move(text));
Ethan Nicholasb33fa3f2020-08-06 13:00:19 -0400407 fSource = source;
Ethan Nicholas8da1e652019-05-24 11:01:59 -0400408 Program::Settings settings;
Ethan Nicholasa11035b2019-11-26 16:27:47 -0500409#if !defined(SKSL_STANDALONE) & SK_SUPPORT_GPU
410 GrContextOptions opts;
411 GrShaderCaps caps(opts);
412 settings.fCaps = &caps;
413#endif
John Stiles881a10c2020-09-19 10:13:24 -0400414 SkASSERT(fIRGenerator->fCanInline);
415 fIRGenerator->fCanInline = false;
Brian Osmane498b3c2020-09-23 14:42:11 -0400416 fIRGenerator->start(&settings, base ? base : fRootSymbolTable, nullptr, true);
Ethan Nicholasb33fa3f2020-08-06 13:00:19 -0400417 fIRGenerator->convertProgram(kind, source->c_str(), source->length(), outElements);
John Stiles881a10c2020-09-19 10:13:24 -0400418 fIRGenerator->fCanInline = true;
Ethan Nicholas8da1e652019-05-24 11:01:59 -0400419 if (this->fErrorCount) {
420 printf("Unexpected errors: %s\n", this->fErrorText.c_str());
John Stiles88f3b682020-10-06 13:37:52 -0400421 SkDEBUGFAILF("%s %s\n", path, this->fErrorText.c_str());
Ethan Nicholas8da1e652019-05-24 11:01:59 -0400422 }
Ethan Nicholas8da1e652019-05-24 11:01:59 -0400423 *outSymbolTable = fIRGenerator->fSymbolTable;
Ethan Nicholasa11035b2019-11-26 16:27:47 -0500424#ifdef SK_DEBUG
425 fSource = nullptr;
426#endif
Ethan Nicholas041fd0a2020-10-07 16:42:04 -0400427 fModifiers.push_back(fIRGenerator->releaseModifiers());
Brian Osmane498b3c2020-09-23 14:42:11 -0400428 fIRGenerator->finish();
Ethan Nicholas8da1e652019-05-24 11:01:59 -0400429}
430
ethannicholas22f939e2016-10-13 13:25:34 -0700431// add the definition created by assigning to the lvalue to the definition set
Ethan Nicholas86a43402017-01-19 13:32:00 -0500432void Compiler::addDefinition(const Expression* lvalue, std::unique_ptr<Expression>* expr,
433 DefinitionMap* definitions) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400434 switch (lvalue->kind()) {
435 case Expression::Kind::kVariableReference: {
Brian Osman79457ef2020-09-24 15:01:27 -0400436 const Variable& var = *lvalue->as<VariableReference>().fVariable;
Ethan Nicholas041fd0a2020-10-07 16:42:04 -0400437 if (var.storage() == Variable::kLocal_Storage) {
ethannicholas22f939e2016-10-13 13:25:34 -0700438 (*definitions)[&var] = expr;
439 }
440 break;
441 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400442 case Expression::Kind::kSwizzle:
ethannicholas22f939e2016-10-13 13:25:34 -0700443 // We consider the variable written to as long as at least some of its components have
444 // been written to. This will lead to some false negatives (we won't catch it if you
445 // write to foo.x and then read foo.y), but being stricter could lead to false positives
Mike Klein6ad99092016-10-26 10:35:22 -0400446 // (we write to foo.x, and then pass foo to a function which happens to only read foo.x,
447 // 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 -0700448 // more complicated whole-program analysis. This is probably good enough.
John Stilesa5a97b42020-08-18 11:19:07 -0400449 this->addDefinition(lvalue->as<Swizzle>().fBase.get(),
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400450 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
ethannicholas22f939e2016-10-13 13:25:34 -0700451 definitions);
452 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400453 case Expression::Kind::kIndex:
ethannicholas22f939e2016-10-13 13:25:34 -0700454 // see comments in Swizzle
John Stilesa5a97b42020-08-18 11:19:07 -0400455 this->addDefinition(lvalue->as<IndexExpression>().fBase.get(),
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400456 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
ethannicholas22f939e2016-10-13 13:25:34 -0700457 definitions);
458 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400459 case Expression::Kind::kFieldAccess:
ethannicholas22f939e2016-10-13 13:25:34 -0700460 // see comments in Swizzle
John Stilesa5a97b42020-08-18 11:19:07 -0400461 this->addDefinition(lvalue->as<FieldAccess>().fBase.get(),
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400462 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
ethannicholas22f939e2016-10-13 13:25:34 -0700463 definitions);
464 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400465 case Expression::Kind::kTernary:
Ethan Nicholasa583b812018-01-18 13:32:11 -0500466 // To simplify analysis, we just pretend that we write to both sides of the ternary.
467 // This allows for false positives (meaning we fail to detect that a variable might not
468 // have been assigned), but is preferable to false negatives.
John Stilesa5a97b42020-08-18 11:19:07 -0400469 this->addDefinition(lvalue->as<TernaryExpression>().fIfTrue.get(),
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400470 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
Ethan Nicholasa583b812018-01-18 13:32:11 -0500471 definitions);
John Stilesa5a97b42020-08-18 11:19:07 -0400472 this->addDefinition(lvalue->as<TernaryExpression>().fIfFalse.get(),
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400473 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
Ethan Nicholasa583b812018-01-18 13:32:11 -0500474 definitions);
475 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400476 case Expression::Kind::kExternalValue:
Ethan Nicholas91164d12019-05-15 15:29:54 -0400477 break;
ethannicholas22f939e2016-10-13 13:25:34 -0700478 default:
479 // not an lvalue, can't happen
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400480 SkASSERT(false);
ethannicholas22f939e2016-10-13 13:25:34 -0700481 }
482}
483
484// add local variables defined by this node to the set
Mike Klein6ad99092016-10-26 10:35:22 -0400485void Compiler::addDefinitions(const BasicBlock::Node& node,
Ethan Nicholas86a43402017-01-19 13:32:00 -0500486 DefinitionMap* definitions) {
John Stiles70025e52020-09-28 16:08:58 -0400487 if (node.isExpression()) {
488 Expression* expr = node.expression()->get();
489 switch (expr->kind()) {
490 case Expression::Kind::kBinary: {
491 BinaryExpression* b = &expr->as<BinaryExpression>();
492 if (b->getOperator() == Token::Kind::TK_EQ) {
493 this->addDefinition(&b->left(), &b->rightPointer(), definitions);
494 } else if (Compiler::IsAssignment(b->getOperator())) {
495 this->addDefinition(
496 &b->left(),
497 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
498 definitions);
Ethan Nicholas86a43402017-01-19 13:32:00 -0500499
ethannicholas22f939e2016-10-13 13:25:34 -0700500 }
John Stiles70025e52020-09-28 16:08:58 -0400501 break;
ethannicholas22f939e2016-10-13 13:25:34 -0700502 }
John Stiles70025e52020-09-28 16:08:58 -0400503 case Expression::Kind::kFunctionCall: {
504 const FunctionCall& c = expr->as<FunctionCall>();
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400505 for (size_t i = 0; i < c.function().fParameters.size(); ++i) {
Ethan Nicholas041fd0a2020-10-07 16:42:04 -0400506 if (c.function().fParameters[i]->modifiers().fFlags & Modifiers::kOut_Flag) {
John Stiles70025e52020-09-28 16:08:58 -0400507 this->addDefinition(
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400508 c.arguments()[i].get(),
John Stiles70025e52020-09-28 16:08:58 -0400509 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
510 definitions);
511 }
512 }
513 break;
514 }
515 case Expression::Kind::kPrefix: {
516 const PrefixExpression* p = &expr->as<PrefixExpression>();
517 if (p->fOperator == Token::Kind::TK_MINUSMINUS ||
518 p->fOperator == Token::Kind::TK_PLUSPLUS) {
519 this->addDefinition(
520 p->fOperand.get(),
521 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
522 definitions);
523 }
524 break;
525 }
526 case Expression::Kind::kPostfix: {
527 const PostfixExpression* p = &expr->as<PostfixExpression>();
528 if (p->fOperator == Token::Kind::TK_MINUSMINUS ||
529 p->fOperator == Token::Kind::TK_PLUSPLUS) {
530 this->addDefinition(
531 p->fOperand.get(),
532 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
533 definitions);
534 }
535 break;
536 }
537 case Expression::Kind::kVariableReference: {
538 const VariableReference* v = &expr->as<VariableReference>();
539 if (v->fRefKind != VariableReference::kRead_RefKind) {
540 this->addDefinition(
541 v,
542 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
543 definitions);
544 }
545 break;
546 }
547 default:
548 break;
ethannicholas22f939e2016-10-13 13:25:34 -0700549 }
John Stiles70025e52020-09-28 16:08:58 -0400550 } else if (node.isStatement()) {
551 Statement* stmt = node.statement()->get();
552 if (stmt->is<VarDeclaration>()) {
553 VarDeclaration& vd = stmt->as<VarDeclaration>();
554 if (vd.fValue) {
555 (*definitions)[vd.fVar] = &vd.fValue;
ethannicholas22f939e2016-10-13 13:25:34 -0700556 }
ethannicholas22f939e2016-10-13 13:25:34 -0700557 }
558 }
559}
560
John Stilese6150002020-10-05 12:03:53 -0400561void Compiler::scanCFG(CFG* cfg, BlockId blockId, SkBitSet* processedSet) {
ethannicholas22f939e2016-10-13 13:25:34 -0700562 BasicBlock& block = cfg->fBlocks[blockId];
563
564 // compute definitions after this block
Ethan Nicholas86a43402017-01-19 13:32:00 -0500565 DefinitionMap after = block.fBefore;
ethannicholas22f939e2016-10-13 13:25:34 -0700566 for (const BasicBlock::Node& n : block.fNodes) {
567 this->addDefinitions(n, &after);
568 }
569
570 // propagate definitions to exits
571 for (BlockId exitId : block.fExits) {
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400572 if (exitId == blockId) {
573 continue;
574 }
ethannicholas22f939e2016-10-13 13:25:34 -0700575 BasicBlock& exit = cfg->fBlocks[exitId];
576 for (const auto& pair : after) {
Ethan Nicholas86a43402017-01-19 13:32:00 -0500577 std::unique_ptr<Expression>* e1 = pair.second;
578 auto found = exit.fBefore.find(pair.first);
579 if (found == exit.fBefore.end()) {
John Stilese6150002020-10-05 12:03:53 -0400580 // exit has no definition for it, just copy it and reprocess exit block
581 processedSet->reset(exitId);
ethannicholas22f939e2016-10-13 13:25:34 -0700582 exit.fBefore[pair.first] = e1;
583 } else {
Ethan Nicholas86a43402017-01-19 13:32:00 -0500584 // exit has a (possibly different) value already defined
585 std::unique_ptr<Expression>* e2 = exit.fBefore[pair.first];
ethannicholas22f939e2016-10-13 13:25:34 -0700586 if (e1 != e2) {
John Stilese6150002020-10-05 12:03:53 -0400587 // definition has changed, merge and reprocess the exit block
588 processedSet->reset(exitId);
Ethan Nicholasaf197692017-02-27 13:26:45 -0500589 if (e1 && e2) {
590 exit.fBefore[pair.first] =
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400591 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression;
Ethan Nicholasaf197692017-02-27 13:26:45 -0500592 } else {
593 exit.fBefore[pair.first] = nullptr;
594 }
ethannicholas22f939e2016-10-13 13:25:34 -0700595 }
596 }
597 }
598 }
599}
600
601// returns a map which maps all local variables in the function to null, indicating that their value
602// is initially unknown
Ethan Nicholas86a43402017-01-19 13:32:00 -0500603static DefinitionMap compute_start_state(const CFG& cfg) {
604 DefinitionMap result;
Mike Klein6ad99092016-10-26 10:35:22 -0400605 for (const auto& block : cfg.fBlocks) {
606 for (const auto& node : block.fNodes) {
John Stiles70025e52020-09-28 16:08:58 -0400607 if (node.isStatement()) {
Ethan Nicholascb670962017-04-20 19:31:52 -0400608 const Statement* s = node.statement()->get();
Brian Osmanc0213602020-10-06 14:43:32 -0400609 if (s->is<VarDeclaration>()) {
610 result[s->as<VarDeclaration>().fVar] = nullptr;
ethannicholas22f939e2016-10-13 13:25:34 -0700611 }
612 }
613 }
614 }
615 return result;
616}
617
Ethan Nicholascb670962017-04-20 19:31:52 -0400618/**
619 * Returns true if assigning to this lvalue has no effect.
620 */
621static bool is_dead(const Expression& lvalue) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400622 switch (lvalue.kind()) {
623 case Expression::Kind::kVariableReference:
Brian Osman79457ef2020-09-24 15:01:27 -0400624 return lvalue.as<VariableReference>().fVariable->dead();
Ethan Nicholase6592142020-09-08 10:22:09 -0400625 case Expression::Kind::kSwizzle:
John Stilesa5a97b42020-08-18 11:19:07 -0400626 return is_dead(*lvalue.as<Swizzle>().fBase);
Ethan Nicholase6592142020-09-08 10:22:09 -0400627 case Expression::Kind::kFieldAccess:
John Stilesa5a97b42020-08-18 11:19:07 -0400628 return is_dead(*lvalue.as<FieldAccess>().fBase);
Ethan Nicholase6592142020-09-08 10:22:09 -0400629 case Expression::Kind::kIndex: {
John Stilesa5a97b42020-08-18 11:19:07 -0400630 const IndexExpression& idx = lvalue.as<IndexExpression>();
Ethan Nicholas2a099da2020-01-02 14:40:54 -0500631 return is_dead(*idx.fBase) &&
632 !idx.fIndex->hasProperty(Expression::Property::kSideEffects);
Ethan Nicholascb670962017-04-20 19:31:52 -0400633 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400634 case Expression::Kind::kTernary: {
John Stilesa5a97b42020-08-18 11:19:07 -0400635 const TernaryExpression& t = lvalue.as<TernaryExpression>();
Ethan Nicholasa583b812018-01-18 13:32:11 -0500636 return !t.fTest->hasSideEffects() && is_dead(*t.fIfTrue) && is_dead(*t.fIfFalse);
637 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400638 case Expression::Kind::kExternalValue:
Ethan Nicholas91164d12019-05-15 15:29:54 -0400639 return false;
Ethan Nicholascb670962017-04-20 19:31:52 -0400640 default:
Ethan Nicholas2a099da2020-01-02 14:40:54 -0500641#ifdef SK_DEBUG
Ethan Nicholascb670962017-04-20 19:31:52 -0400642 ABORT("invalid lvalue: %s\n", lvalue.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -0500643#endif
644 return false;
Ethan Nicholascb670962017-04-20 19:31:52 -0400645 }
646}
ethannicholas22f939e2016-10-13 13:25:34 -0700647
Ethan Nicholascb670962017-04-20 19:31:52 -0400648/**
649 * Returns true if this is an assignment which can be collapsed down to just the right hand side due
650 * to a dead target and lack of side effects on the left hand side.
651 */
652static bool dead_assignment(const BinaryExpression& b) {
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400653 if (!Compiler::IsAssignment(b.getOperator())) {
Ethan Nicholascb670962017-04-20 19:31:52 -0400654 return false;
655 }
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400656 return is_dead(b.left());
Ethan Nicholascb670962017-04-20 19:31:52 -0400657}
658
659void Compiler::computeDataFlow(CFG* cfg) {
660 cfg->fBlocks[cfg->fStart].fBefore = compute_start_state(*cfg);
John Stilese6150002020-10-05 12:03:53 -0400661
662 // We set bits in the "processed" set after a block has been scanned.
663 SkBitSet processedSet(cfg->fBlocks.size());
664 while (SkBitSet::OptionalIndex blockId = processedSet.findFirstUnset()) {
665 processedSet.set(*blockId);
666 this->scanCFG(cfg, *blockId, &processedSet);
ethannicholas22f939e2016-10-13 13:25:34 -0700667 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400668}
669
670/**
671 * Attempts to replace the expression pointed to by iter with a new one (in both the CFG and the
672 * IR). If the expression can be cleanly removed, returns true and updates the iterator to point to
673 * the newly-inserted element. Otherwise updates only the IR and returns false (and the CFG will
674 * need to be regenerated).
675 */
John Stilesafbf8992020-08-18 10:08:21 -0400676static bool try_replace_expression(BasicBlock* b,
677 std::vector<BasicBlock::Node>::iterator* iter,
678 std::unique_ptr<Expression>* newExpression) {
Ethan Nicholascb670962017-04-20 19:31:52 -0400679 std::unique_ptr<Expression>* target = (*iter)->expression();
680 if (!b->tryRemoveExpression(iter)) {
681 *target = std::move(*newExpression);
682 return false;
683 }
684 *target = std::move(*newExpression);
685 return b->tryInsertExpression(iter, target);
686}
687
688/**
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400689 * Returns true if the expression is a constant numeric literal with the specified value, or a
690 * constant vector with all elements equal to the specified value.
Ethan Nicholascb670962017-04-20 19:31:52 -0400691 */
Ethan Nicholasa3f22f12020-10-01 12:13:17 -0400692template <typename T = SKSL_FLOAT>
John Stiles9d944232020-08-19 09:56:49 -0400693static bool is_constant(const Expression& expr, T value) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400694 switch (expr.kind()) {
695 case Expression::Kind::kIntLiteral:
Ethan Nicholase96cdd12020-09-28 16:27:18 -0400696 return expr.as<IntLiteral>().value() == value;
John Stiles9d944232020-08-19 09:56:49 -0400697
Ethan Nicholase6592142020-09-08 10:22:09 -0400698 case Expression::Kind::kFloatLiteral:
Ethan Nicholasa3f22f12020-10-01 12:13:17 -0400699 return expr.as<FloatLiteral>().value() == value;
John Stiles9d944232020-08-19 09:56:49 -0400700
Ethan Nicholase6592142020-09-08 10:22:09 -0400701 case Expression::Kind::kConstructor: {
John Stiles9d944232020-08-19 09:56:49 -0400702 const Constructor& constructor = expr.as<Constructor>();
703 if (constructor.isCompileTimeConstant()) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400704 const Type& constructorType = constructor.type();
705 bool isFloat = constructorType.columns() > 1
706 ? constructorType.componentType().isFloat()
707 : constructorType.isFloat();
708 switch (constructorType.typeKind()) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400709 case Type::TypeKind::kVector:
Ethan Nicholas30d30222020-09-11 12:27:26 -0400710 for (int i = 0; i < constructorType.columns(); ++i) {
John Stiles9d944232020-08-19 09:56:49 -0400711 if (isFloat) {
712 if (constructor.getFVecComponent(i) != value) {
713 return false;
714 }
715 } else {
716 if (constructor.getIVecComponent(i) != value) {
717 return false;
718 }
719 }
Ethan Nicholasd188c182019-06-10 15:55:38 -0400720 }
John Stiles9d944232020-08-19 09:56:49 -0400721 return true;
722
Ethan Nicholase6592142020-09-08 10:22:09 -0400723 case Type::TypeKind::kScalar:
Ethan Nicholasf70f0442020-09-29 12:41:35 -0400724 SkASSERT(constructor.arguments().size() == 1);
725 return is_constant<T>(*constructor.arguments()[0], value);
John Stiles9d944232020-08-19 09:56:49 -0400726
727 default:
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400728 return false;
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400729 }
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400730 }
731 return false;
732 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400733 default:
734 return false;
735 }
736}
737
738/**
739 * Collapses the binary expression pointed to by iter down to just the right side (in both the IR
740 * and CFG structures).
741 */
John Stilesafbf8992020-08-18 10:08:21 -0400742static void delete_left(BasicBlock* b,
743 std::vector<BasicBlock::Node>::iterator* iter,
744 bool* outUpdated,
745 bool* outNeedsRescan) {
Ethan Nicholascb670962017-04-20 19:31:52 -0400746 *outUpdated = true;
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400747 std::unique_ptr<Expression>* target = (*iter)->expression();
John Stilesa5a97b42020-08-18 11:19:07 -0400748 BinaryExpression& bin = (*target)->as<BinaryExpression>();
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400749 Expression& left = bin.left();
750 std::unique_ptr<Expression>& rightPointer = bin.rightPointer();
751 SkASSERT(!left.hasSideEffects());
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400752 bool result;
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400753 if (bin.getOperator() == Token::Kind::TK_EQ) {
754 result = b->tryRemoveLValueBefore(iter, &left);
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400755 } else {
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400756 result = b->tryRemoveExpressionBefore(iter, &left);
Ethan Nicholascb670962017-04-20 19:31:52 -0400757 }
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400758 *target = std::move(rightPointer);
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400759 if (!result) {
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400760 *outNeedsRescan = true;
761 return;
762 }
763 if (*iter == b->fNodes.begin()) {
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400764 *outNeedsRescan = true;
765 return;
766 }
767 --(*iter);
John Stiles70025e52020-09-28 16:08:58 -0400768 if (!(*iter)->isExpression() || (*iter)->expression() != &rightPointer) {
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400769 *outNeedsRescan = true;
770 return;
771 }
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400772 *iter = b->fNodes.erase(*iter);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400773 SkASSERT((*iter)->expression() == target);
Ethan Nicholascb670962017-04-20 19:31:52 -0400774}
775
776/**
777 * Collapses the binary expression pointed to by iter down to just the left side (in both the IR and
778 * CFG structures).
779 */
John Stilesafbf8992020-08-18 10:08:21 -0400780static void delete_right(BasicBlock* b,
781 std::vector<BasicBlock::Node>::iterator* iter,
782 bool* outUpdated,
783 bool* outNeedsRescan) {
Ethan Nicholascb670962017-04-20 19:31:52 -0400784 *outUpdated = true;
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400785 std::unique_ptr<Expression>* target = (*iter)->expression();
John Stilesa5a97b42020-08-18 11:19:07 -0400786 BinaryExpression& bin = (*target)->as<BinaryExpression>();
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400787 std::unique_ptr<Expression>& leftPointer = bin.leftPointer();
788 Expression& right = bin.right();
789 SkASSERT(!right.hasSideEffects());
790 if (!b->tryRemoveExpressionBefore(iter, &right)) {
791 *target = std::move(leftPointer);
Ethan Nicholascb670962017-04-20 19:31:52 -0400792 *outNeedsRescan = true;
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400793 return;
Ethan Nicholascb670962017-04-20 19:31:52 -0400794 }
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400795 *target = std::move(leftPointer);
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400796 if (*iter == b->fNodes.begin()) {
797 *outNeedsRescan = true;
798 return;
799 }
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400800 --(*iter);
John Stiles70025e52020-09-28 16:08:58 -0400801 if ((!(*iter)->isExpression() || (*iter)->expression() != &leftPointer)) {
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400802 *outNeedsRescan = true;
803 return;
804 }
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400805 *iter = b->fNodes.erase(*iter);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400806 SkASSERT((*iter)->expression() == target);
Ethan Nicholascb670962017-04-20 19:31:52 -0400807}
808
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400809/**
810 * Constructs the specified type using a single argument.
811 */
Ethan Nicholas30d30222020-09-11 12:27:26 -0400812static std::unique_ptr<Expression> construct(const Type* type, std::unique_ptr<Expression> v) {
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400813 std::vector<std::unique_ptr<Expression>> args;
814 args.push_back(std::move(v));
Ethan Nicholase6592142020-09-08 10:22:09 -0400815 std::unique_ptr<Expression> result = std::make_unique<Constructor>(-1, type, std::move(args));
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400816 return result;
817}
818
819/**
820 * Used in the implementations of vectorize_left and vectorize_right. Given a vector type and an
821 * expression x, deletes the expression pointed to by iter and replaces it with <type>(x).
822 */
823static void vectorize(BasicBlock* b,
824 std::vector<BasicBlock::Node>::iterator* iter,
825 const Type& type,
826 std::unique_ptr<Expression>* otherExpression,
827 bool* outUpdated,
828 bool* outNeedsRescan) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400829 SkASSERT((*(*iter)->expression())->kind() == Expression::Kind::kBinary);
830 SkASSERT(type.typeKind() == Type::TypeKind::kVector);
Ethan Nicholas30d30222020-09-11 12:27:26 -0400831 SkASSERT((*otherExpression)->type().typeKind() == Type::TypeKind::kScalar);
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400832 *outUpdated = true;
833 std::unique_ptr<Expression>* target = (*iter)->expression();
834 if (!b->tryRemoveExpression(iter)) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400835 *target = construct(&type, std::move(*otherExpression));
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400836 *outNeedsRescan = true;
837 } else {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400838 *target = construct(&type, std::move(*otherExpression));
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400839 if (!b->tryInsertExpression(iter, target)) {
840 *outNeedsRescan = true;
841 }
842 }
843}
844
845/**
846 * Given a binary expression of the form x <op> vec<n>(y), deletes the right side and vectorizes the
847 * left to yield vec<n>(x).
848 */
849static void vectorize_left(BasicBlock* b,
850 std::vector<BasicBlock::Node>::iterator* iter,
851 bool* outUpdated,
852 bool* outNeedsRescan) {
John Stilesa5a97b42020-08-18 11:19:07 -0400853 BinaryExpression& bin = (*(*iter)->expression())->as<BinaryExpression>();
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400854 vectorize(b, iter, bin.right().type(), &bin.leftPointer(), outUpdated, outNeedsRescan);
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400855}
856
857/**
858 * Given a binary expression of the form vec<n>(x) <op> y, deletes the left side and vectorizes the
859 * right to yield vec<n>(y).
860 */
861static void vectorize_right(BasicBlock* b,
862 std::vector<BasicBlock::Node>::iterator* iter,
863 bool* outUpdated,
864 bool* outNeedsRescan) {
John Stilesa5a97b42020-08-18 11:19:07 -0400865 BinaryExpression& bin = (*(*iter)->expression())->as<BinaryExpression>();
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400866 vectorize(b, iter, bin.left().type(), &bin.rightPointer(), outUpdated, outNeedsRescan);
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400867}
868
869// Mark that an expression which we were writing to is no longer being written to
John Stilesa5a97b42020-08-18 11:19:07 -0400870static void clear_write(Expression& expr) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400871 switch (expr.kind()) {
872 case Expression::Kind::kVariableReference: {
John Stilesa5a97b42020-08-18 11:19:07 -0400873 expr.as<VariableReference>().setRefKind(VariableReference::kRead_RefKind);
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400874 break;
875 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400876 case Expression::Kind::kFieldAccess:
John Stilesa5a97b42020-08-18 11:19:07 -0400877 clear_write(*expr.as<FieldAccess>().fBase);
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400878 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400879 case Expression::Kind::kSwizzle:
John Stilesa5a97b42020-08-18 11:19:07 -0400880 clear_write(*expr.as<Swizzle>().fBase);
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400881 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400882 case Expression::Kind::kIndex:
John Stilesa5a97b42020-08-18 11:19:07 -0400883 clear_write(*expr.as<IndexExpression>().fBase);
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400884 break;
885 default:
886 ABORT("shouldn't be writing to this kind of expression\n");
887 break;
888 }
889}
890
Ethan Nicholascb670962017-04-20 19:31:52 -0400891void Compiler::simplifyExpression(DefinitionMap& definitions,
892 BasicBlock& b,
893 std::vector<BasicBlock::Node>::iterator* iter,
894 std::unordered_set<const Variable*>* undefinedVariables,
895 bool* outUpdated,
896 bool* outNeedsRescan) {
897 Expression* expr = (*iter)->expression()->get();
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400898 SkASSERT(expr);
Ethan Nicholascb670962017-04-20 19:31:52 -0400899 if ((*iter)->fConstantPropagation) {
900 std::unique_ptr<Expression> optimized = expr->constantPropagate(*fIRGenerator, definitions);
901 if (optimized) {
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400902 *outUpdated = true;
Ethan Nicholas30d30222020-09-11 12:27:26 -0400903 optimized = fIRGenerator->coerce(std::move(optimized), expr->type());
Ethan Nicholas1d881522020-09-11 09:32:54 -0400904 SkASSERT(optimized);
Ethan Nicholascb670962017-04-20 19:31:52 -0400905 if (!try_replace_expression(&b, iter, &optimized)) {
906 *outNeedsRescan = true;
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400907 return;
Ethan Nicholascb670962017-04-20 19:31:52 -0400908 }
John Stiles70025e52020-09-28 16:08:58 -0400909 SkASSERT((*iter)->isExpression());
Ethan Nicholascb670962017-04-20 19:31:52 -0400910 expr = (*iter)->expression()->get();
Ethan Nicholascb670962017-04-20 19:31:52 -0400911 }
912 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400913 switch (expr->kind()) {
914 case Expression::Kind::kVariableReference: {
John Stilesa5a97b42020-08-18 11:19:07 -0400915 const VariableReference& ref = expr->as<VariableReference>();
Brian Osman79457ef2020-09-24 15:01:27 -0400916 const Variable* var = ref.fVariable;
Ethan Nicholas8f7e28f2018-03-26 14:24:27 -0400917 if (ref.refKind() != VariableReference::kWrite_RefKind &&
918 ref.refKind() != VariableReference::kPointer_RefKind &&
Ethan Nicholas041fd0a2020-10-07 16:42:04 -0400919 var->storage() == Variable::kLocal_Storage && !definitions[var] &&
Brian Osman79457ef2020-09-24 15:01:27 -0400920 (*undefinedVariables).find(var) == (*undefinedVariables).end()) {
921 (*undefinedVariables).insert(var);
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000922 this->error(expr->fOffset,
Ethan Nicholase2c49992020-10-05 11:49:11 -0400923 "'" + var->name() + "' has not been assigned");
Ethan Nicholascb670962017-04-20 19:31:52 -0400924 }
925 break;
926 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400927 case Expression::Kind::kTernary: {
John Stiles403a3632020-08-20 12:11:48 -0400928 TernaryExpression* t = &expr->as<TernaryExpression>();
Ethan Nicholase6592142020-09-08 10:22:09 -0400929 if (t->fTest->kind() == Expression::Kind::kBoolLiteral) {
Ethan Nicholascb670962017-04-20 19:31:52 -0400930 // ternary has a constant test, replace it with either the true or
931 // false branch
Ethan Nicholas59d660c2020-09-28 09:18:15 -0400932 if (t->fTest->as<BoolLiteral>().value()) {
Ethan Nicholascb670962017-04-20 19:31:52 -0400933 (*iter)->setExpression(std::move(t->fIfTrue));
934 } else {
935 (*iter)->setExpression(std::move(t->fIfFalse));
936 }
937 *outUpdated = true;
938 *outNeedsRescan = true;
939 }
940 break;
941 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400942 case Expression::Kind::kBinary: {
John Stiles403a3632020-08-20 12:11:48 -0400943 BinaryExpression* bin = &expr->as<BinaryExpression>();
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400944 if (dead_assignment(*bin)) {
945 delete_left(&b, iter, outUpdated, outNeedsRescan);
946 break;
947 }
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400948 Expression& left = bin->left();
949 Expression& right = bin->right();
950 const Type& leftType = left.type();
951 const Type& rightType = right.type();
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400952 // collapse useless expressions like x * 1 or x + 0
Ethan Nicholas30d30222020-09-11 12:27:26 -0400953 if (((leftType.typeKind() != Type::TypeKind::kScalar) &&
954 (leftType.typeKind() != Type::TypeKind::kVector)) ||
955 ((rightType.typeKind() != Type::TypeKind::kScalar) &&
956 (rightType.typeKind() != Type::TypeKind::kVector))) {
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400957 break;
958 }
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400959 switch (bin->getOperator()) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400960 case Token::Kind::TK_STAR:
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400961 if (is_constant(left, 1)) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400962 if (leftType.typeKind() == Type::TypeKind::kVector &&
963 rightType.typeKind() == Type::TypeKind::kScalar) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400964 // float4(1) * x -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400965 vectorize_right(&b, iter, outUpdated, outNeedsRescan);
966 } else {
967 // 1 * x -> x
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400968 // 1 * float4(x) -> float4(x)
969 // float4(1) * float4(x) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400970 delete_left(&b, iter, outUpdated, outNeedsRescan);
971 }
972 }
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400973 else if (is_constant(left, 0)) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400974 if (leftType.typeKind() == Type::TypeKind::kScalar &&
975 rightType.typeKind() == Type::TypeKind::kVector &&
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400976 !right.hasSideEffects()) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400977 // 0 * float4(x) -> float4(0)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400978 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
979 } else {
980 // 0 * x -> 0
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400981 // float4(0) * x -> float4(0)
982 // float4(0) * float4(x) -> float4(0)
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400983 if (!right.hasSideEffects()) {
Ethan Nicholas51493ee2017-12-11 12:34:33 -0500984 delete_right(&b, iter, outUpdated, outNeedsRescan);
985 }
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400986 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400987 }
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400988 else if (is_constant(right, 1)) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400989 if (leftType.typeKind() == Type::TypeKind::kScalar &&
990 rightType.typeKind() == Type::TypeKind::kVector) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400991 // x * float4(1) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400992 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
993 } else {
994 // x * 1 -> x
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400995 // float4(x) * 1 -> float4(x)
996 // float4(x) * float4(1) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400997 delete_right(&b, iter, outUpdated, outNeedsRescan);
998 }
999 }
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001000 else if (is_constant(right, 0)) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04001001 if (leftType.typeKind() == Type::TypeKind::kVector &&
1002 rightType.typeKind() == Type::TypeKind::kScalar &&
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001003 !left.hasSideEffects()) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -04001004 // float4(x) * 0 -> float4(0)
Ethan Nicholasfe53e582017-04-27 16:24:51 -04001005 vectorize_right(&b, iter, outUpdated, outNeedsRescan);
1006 } else {
1007 // x * 0 -> 0
Ethan Nicholas5af9ea32017-07-28 15:19:46 -04001008 // x * float4(0) -> float4(0)
1009 // float4(x) * float4(0) -> float4(0)
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001010 if (!left.hasSideEffects()) {
Ethan Nicholas51493ee2017-12-11 12:34:33 -05001011 delete_left(&b, iter, outUpdated, outNeedsRescan);
1012 }
Ethan Nicholasfe53e582017-04-27 16:24:51 -04001013 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001014 }
1015 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001016 case Token::Kind::TK_PLUS:
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001017 if (is_constant(left, 0)) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04001018 if (leftType.typeKind() == Type::TypeKind::kVector &&
1019 rightType.typeKind() == Type::TypeKind::kScalar) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -04001020 // float4(0) + x -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -04001021 vectorize_right(&b, iter, outUpdated, outNeedsRescan);
1022 } else {
1023 // 0 + x -> x
Ethan Nicholas5af9ea32017-07-28 15:19:46 -04001024 // 0 + float4(x) -> float4(x)
1025 // float4(0) + float4(x) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -04001026 delete_left(&b, iter, outUpdated, outNeedsRescan);
1027 }
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001028 } else if (is_constant(right, 0)) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04001029 if (leftType.typeKind() == Type::TypeKind::kScalar &&
1030 rightType.typeKind() == Type::TypeKind::kVector) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -04001031 // x + float4(0) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -04001032 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
1033 } else {
1034 // x + 0 -> x
Ethan Nicholas5af9ea32017-07-28 15:19:46 -04001035 // float4(x) + 0 -> float4(x)
1036 // float4(x) + float4(0) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -04001037 delete_right(&b, iter, outUpdated, outNeedsRescan);
1038 }
Ethan Nicholas56e42712017-04-21 10:23:37 -04001039 }
1040 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001041 case Token::Kind::TK_MINUS:
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001042 if (is_constant(right, 0)) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04001043 if (leftType.typeKind() == Type::TypeKind::kScalar &&
1044 rightType.typeKind() == Type::TypeKind::kVector) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -04001045 // x - float4(0) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -04001046 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
1047 } else {
1048 // x - 0 -> x
Ethan Nicholas5af9ea32017-07-28 15:19:46 -04001049 // float4(x) - 0 -> float4(x)
1050 // float4(x) - float4(0) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -04001051 delete_right(&b, iter, outUpdated, outNeedsRescan);
1052 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001053 }
1054 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001055 case Token::Kind::TK_SLASH:
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001056 if (is_constant(right, 1)) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04001057 if (leftType.typeKind() == Type::TypeKind::kScalar &&
1058 rightType.typeKind() == Type::TypeKind::kVector) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -04001059 // x / float4(1) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -04001060 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
1061 } else {
1062 // x / 1 -> x
Ethan Nicholas5af9ea32017-07-28 15:19:46 -04001063 // float4(x) / 1 -> float4(x)
1064 // float4(x) / float4(1) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -04001065 delete_right(&b, iter, outUpdated, outNeedsRescan);
1066 }
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001067 } else if (is_constant(left, 0)) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04001068 if (leftType.typeKind() == Type::TypeKind::kScalar &&
1069 rightType.typeKind() == Type::TypeKind::kVector &&
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001070 !right.hasSideEffects()) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -04001071 // 0 / float4(x) -> float4(0)
Ethan Nicholasfe53e582017-04-27 16:24:51 -04001072 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
1073 } else {
1074 // 0 / x -> 0
Ethan Nicholas5af9ea32017-07-28 15:19:46 -04001075 // float4(0) / x -> float4(0)
1076 // float4(0) / float4(x) -> float4(0)
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001077 if (!right.hasSideEffects()) {
Ethan Nicholas51493ee2017-12-11 12:34:33 -05001078 delete_right(&b, iter, outUpdated, outNeedsRescan);
1079 }
Ethan Nicholasfe53e582017-04-27 16:24:51 -04001080 }
1081 }
1082 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001083 case Token::Kind::TK_PLUSEQ:
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001084 if (is_constant(right, 0)) {
1085 clear_write(left);
Ethan Nicholasfe53e582017-04-27 16:24:51 -04001086 delete_right(&b, iter, outUpdated, outNeedsRescan);
1087 }
1088 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001089 case Token::Kind::TK_MINUSEQ:
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001090 if (is_constant(right, 0)) {
1091 clear_write(left);
Ethan Nicholasfe53e582017-04-27 16:24:51 -04001092 delete_right(&b, iter, outUpdated, outNeedsRescan);
1093 }
1094 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001095 case Token::Kind::TK_STAREQ:
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001096 if (is_constant(right, 1)) {
1097 clear_write(left);
Ethan Nicholasfe53e582017-04-27 16:24:51 -04001098 delete_right(&b, iter, outUpdated, outNeedsRescan);
1099 }
1100 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001101 case Token::Kind::TK_SLASHEQ:
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001102 if (is_constant(right, 1)) {
1103 clear_write(left);
Ethan Nicholascb670962017-04-20 19:31:52 -04001104 delete_right(&b, iter, outUpdated, outNeedsRescan);
1105 }
1106 break;
1107 default:
1108 break;
1109 }
Ethan Nicholas409f6f02019-09-17 12:34:39 -04001110 break;
1111 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001112 case Expression::Kind::kSwizzle: {
John Stiles403a3632020-08-20 12:11:48 -04001113 Swizzle& s = expr->as<Swizzle>();
Ethan Nicholas409f6f02019-09-17 12:34:39 -04001114 // detect identity swizzles like foo.rgba
Ethan Nicholas30d30222020-09-11 12:27:26 -04001115 if ((int) s.fComponents.size() == s.fBase->type().columns()) {
Ethan Nicholas409f6f02019-09-17 12:34:39 -04001116 bool identity = true;
1117 for (int i = 0; i < (int) s.fComponents.size(); ++i) {
1118 if (s.fComponents[i] != i) {
1119 identity = false;
1120 break;
1121 }
1122 }
1123 if (identity) {
1124 *outUpdated = true;
1125 if (!try_replace_expression(&b, iter, &s.fBase)) {
1126 *outNeedsRescan = true;
1127 return;
1128 }
John Stiles70025e52020-09-28 16:08:58 -04001129 SkASSERT((*iter)->isExpression());
Ethan Nicholas409f6f02019-09-17 12:34:39 -04001130 break;
1131 }
1132 }
1133 // detect swizzles of swizzles, e.g. replace foo.argb.r000 with foo.a000
Ethan Nicholase6592142020-09-08 10:22:09 -04001134 if (s.fBase->kind() == Expression::Kind::kSwizzle) {
John Stilesa5a97b42020-08-18 11:19:07 -04001135 Swizzle& base = s.fBase->as<Swizzle>();
Ethan Nicholas409f6f02019-09-17 12:34:39 -04001136 std::vector<int> final;
1137 for (int c : s.fComponents) {
Brian Osman25647672020-09-15 15:16:56 -04001138 final.push_back(base.fComponents[c]);
Ethan Nicholas409f6f02019-09-17 12:34:39 -04001139 }
1140 *outUpdated = true;
1141 std::unique_ptr<Expression> replacement(new Swizzle(*fContext, base.fBase->clone(),
1142 std::move(final)));
1143 if (!try_replace_expression(&b, iter, &replacement)) {
1144 *outNeedsRescan = true;
1145 return;
1146 }
John Stiles70025e52020-09-28 16:08:58 -04001147 SkASSERT((*iter)->isExpression());
Ethan Nicholas409f6f02019-09-17 12:34:39 -04001148 }
John Stiles30212b72020-06-11 17:55:07 -04001149 break;
Ethan Nicholascb670962017-04-20 19:31:52 -04001150 }
1151 default:
1152 break;
1153 }
1154}
1155
John Stiles92219b42020-06-15 12:32:24 -04001156// Returns true if this statement could potentially execute a break at the current level. We ignore
1157// nested loops and switches, since any breaks inside of them will merely break the loop / switch.
John Stilesb92641c2020-08-31 18:09:01 -04001158static bool contains_conditional_break(Statement& stmt) {
1159 class ContainsConditionalBreak : public ProgramVisitor {
1160 public:
1161 bool visitStatement(const Statement& stmt) override {
Ethan Nicholase6592142020-09-08 10:22:09 -04001162 switch (stmt.kind()) {
1163 case Statement::Kind::kBlock:
John Stilesb92641c2020-08-31 18:09:01 -04001164 return this->INHERITED::visitStatement(stmt);
1165
Ethan Nicholase6592142020-09-08 10:22:09 -04001166 case Statement::Kind::kBreak:
John Stilesb92641c2020-08-31 18:09:01 -04001167 return fInConditional > 0;
1168
Ethan Nicholase6592142020-09-08 10:22:09 -04001169 case Statement::Kind::kIf: {
John Stilesb92641c2020-08-31 18:09:01 -04001170 ++fInConditional;
1171 bool result = this->INHERITED::visitStatement(stmt);
1172 --fInConditional;
1173 return result;
1174 }
1175
1176 default:
1177 return false;
1178 }
1179 }
1180
1181 int fInConditional = 0;
1182 using INHERITED = ProgramVisitor;
1183 };
1184
1185 return ContainsConditionalBreak{}.visitStatement(stmt);
John Stiles92219b42020-06-15 12:32:24 -04001186}
1187
Ethan Nicholas5005a222018-08-24 13:06:27 -04001188// returns true if this statement definitely executes a break at the current level (we ignore
1189// nested loops and switches, since any breaks inside of them will merely break the loop / switch)
John Stilesb92641c2020-08-31 18:09:01 -04001190static bool contains_unconditional_break(Statement& stmt) {
1191 class ContainsUnconditionalBreak : public ProgramVisitor {
1192 public:
1193 bool visitStatement(const Statement& stmt) override {
Ethan Nicholase6592142020-09-08 10:22:09 -04001194 switch (stmt.kind()) {
1195 case Statement::Kind::kBlock:
John Stilesb92641c2020-08-31 18:09:01 -04001196 return this->INHERITED::visitStatement(stmt);
1197
Ethan Nicholase6592142020-09-08 10:22:09 -04001198 case Statement::Kind::kBreak:
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001199 return true;
John Stilesb92641c2020-08-31 18:09:01 -04001200
1201 default:
1202 return false;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001203 }
John Stilesb92641c2020-08-31 18:09:01 -04001204 }
John Stiles92219b42020-06-15 12:32:24 -04001205
John Stilesb92641c2020-08-31 18:09:01 -04001206 using INHERITED = ProgramVisitor;
1207 };
John Stiles92219b42020-06-15 12:32:24 -04001208
John Stilesb92641c2020-08-31 18:09:01 -04001209 return ContainsUnconditionalBreak{}.visitStatement(stmt);
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001210}
1211
John Stiles92219b42020-06-15 12:32:24 -04001212static void move_all_but_break(std::unique_ptr<Statement>& stmt,
1213 std::vector<std::unique_ptr<Statement>>* target) {
Ethan Nicholase6592142020-09-08 10:22:09 -04001214 switch (stmt->kind()) {
1215 case Statement::Kind::kBlock: {
John Stiles92219b42020-06-15 12:32:24 -04001216 // Recurse into the block.
1217 Block& block = static_cast<Block&>(*stmt);
1218
1219 std::vector<std::unique_ptr<Statement>> blockStmts;
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001220 blockStmts.reserve(block.children().size());
1221 for (std::unique_ptr<Statement>& stmt : block.children()) {
1222 move_all_but_break(stmt, &blockStmts);
Ethan Nicholas739e1ca2020-06-11 12:16:14 -04001223 }
John Stiles92219b42020-06-15 12:32:24 -04001224
1225 target->push_back(std::make_unique<Block>(block.fOffset, std::move(blockStmts),
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001226 block.symbolTable(), block.isScope()));
Ethan Nicholas739e1ca2020-06-11 12:16:14 -04001227 break;
John Stiles92219b42020-06-15 12:32:24 -04001228 }
1229
Ethan Nicholase6592142020-09-08 10:22:09 -04001230 case Statement::Kind::kBreak:
John Stiles92219b42020-06-15 12:32:24 -04001231 // Do not append a break to the target.
1232 break;
1233
Ethan Nicholas739e1ca2020-06-11 12:16:14 -04001234 default:
John Stiles92219b42020-06-15 12:32:24 -04001235 // Append normal statements to the target.
1236 target->push_back(std::move(stmt));
1237 break;
Ethan Nicholas739e1ca2020-06-11 12:16:14 -04001238 }
1239}
1240
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001241// Returns a block containing all of the statements that will be run if the given case matches
1242// (which, owing to the statements being owned by unique_ptrs, means the switch itself will be
1243// broken by this call and must then be discarded).
1244// Returns null (and leaves the switch unmodified) if no such simple reduction is possible, such as
1245// when break statements appear inside conditionals.
John Stiles92219b42020-06-15 12:32:24 -04001246static std::unique_ptr<Statement> block_for_case(SwitchStatement* switchStatement,
1247 SwitchCase* caseToCapture) {
1248 // We have to be careful to not move any of the pointers until after we're sure we're going to
1249 // succeed, so before we make any changes at all, we check the switch-cases to decide on a plan
1250 // of action. First, find the switch-case we are interested in.
1251 auto iter = switchStatement->fCases.begin();
1252 for (; iter != switchStatement->fCases.end(); ++iter) {
1253 if (iter->get() == caseToCapture) {
1254 break;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001255 }
John Stiles92219b42020-06-15 12:32:24 -04001256 }
1257
1258 // Next, walk forward through the rest of the switch. If we find a conditional break, we're
1259 // stuck and can't simplify at all. If we find an unconditional break, we have a range of
1260 // statements that we can use for simplification.
1261 auto startIter = iter;
1262 Statement* unconditionalBreakStmt = nullptr;
1263 for (; iter != switchStatement->fCases.end(); ++iter) {
1264 for (std::unique_ptr<Statement>& stmt : (*iter)->fStatements) {
1265 if (contains_conditional_break(*stmt)) {
1266 // We can't reduce switch-cases to a block when they have conditional breaks.
1267 return nullptr;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001268 }
John Stiles92219b42020-06-15 12:32:24 -04001269
1270 if (contains_unconditional_break(*stmt)) {
1271 // We found an unconditional break. We can use this block, but we need to strip
1272 // out the break statement.
1273 unconditionalBreakStmt = stmt.get();
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001274 break;
1275 }
1276 }
John Stiles92219b42020-06-15 12:32:24 -04001277
1278 if (unconditionalBreakStmt != nullptr) {
1279 break;
1280 }
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001281 }
John Stiles92219b42020-06-15 12:32:24 -04001282
1283 // We fell off the bottom of the switch or encountered a break. We know the range of statements
1284 // that we need to move over, and we know it's safe to do so.
1285 std::vector<std::unique_ptr<Statement>> caseStmts;
1286
1287 // We can move over most of the statements as-is.
1288 while (startIter != iter) {
1289 for (std::unique_ptr<Statement>& stmt : (*startIter)->fStatements) {
1290 caseStmts.push_back(std::move(stmt));
1291 }
1292 ++startIter;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001293 }
John Stiles92219b42020-06-15 12:32:24 -04001294
1295 // If we found an unconditional break at the end, we need to move what we can while avoiding
1296 // that break.
1297 if (unconditionalBreakStmt != nullptr) {
1298 for (std::unique_ptr<Statement>& stmt : (*startIter)->fStatements) {
1299 if (stmt.get() == unconditionalBreakStmt) {
1300 move_all_but_break(stmt, &caseStmts);
1301 unconditionalBreakStmt = nullptr;
1302 break;
1303 }
1304
1305 caseStmts.push_back(std::move(stmt));
1306 }
1307 }
1308
1309 SkASSERT(unconditionalBreakStmt == nullptr); // Verify that we fixed the unconditional break.
1310
1311 // Return our newly-synthesized block.
1312 return std::make_unique<Block>(/*offset=*/-1, std::move(caseStmts), switchStatement->fSymbols);
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001313}
1314
Ethan Nicholascb670962017-04-20 19:31:52 -04001315void Compiler::simplifyStatement(DefinitionMap& definitions,
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001316 BasicBlock& b,
1317 std::vector<BasicBlock::Node>::iterator* iter,
1318 std::unordered_set<const Variable*>* undefinedVariables,
1319 bool* outUpdated,
1320 bool* outNeedsRescan) {
Ethan Nicholascb670962017-04-20 19:31:52 -04001321 Statement* stmt = (*iter)->statement()->get();
Ethan Nicholase6592142020-09-08 10:22:09 -04001322 switch (stmt->kind()) {
1323 case Statement::Kind::kVarDeclaration: {
John Stilesa5a97b42020-08-18 11:19:07 -04001324 const auto& varDecl = stmt->as<VarDeclaration>();
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001325 if (varDecl.fVar->dead() &&
1326 (!varDecl.fValue ||
1327 !varDecl.fValue->hasSideEffects())) {
1328 if (varDecl.fValue) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001329 SkASSERT((*iter)->statement()->get() == stmt);
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001330 if (!b.tryRemoveExpressionBefore(iter, varDecl.fValue.get())) {
1331 *outNeedsRescan = true;
Ethan Nicholascb670962017-04-20 19:31:52 -04001332 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001333 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001334 (*iter)->setStatement(std::unique_ptr<Statement>(new Nop()));
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001335 *outUpdated = true;
Ethan Nicholascb670962017-04-20 19:31:52 -04001336 }
1337 break;
1338 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001339 case Statement::Kind::kIf: {
John Stilesa5a97b42020-08-18 11:19:07 -04001340 IfStatement& i = stmt->as<IfStatement>();
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04001341 if (i.test()->kind() == Expression::Kind::kBoolLiteral) {
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001342 // constant if, collapse down to a single branch
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04001343 if (i.test()->as<BoolLiteral>().value()) {
1344 SkASSERT(i.ifTrue());
1345 (*iter)->setStatement(std::move(i.ifTrue()));
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001346 } else {
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04001347 if (i.ifFalse()) {
1348 (*iter)->setStatement(std::move(i.ifFalse()));
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001349 } else {
1350 (*iter)->setStatement(std::unique_ptr<Statement>(new Nop()));
1351 }
1352 }
1353 *outUpdated = true;
1354 *outNeedsRescan = true;
1355 break;
1356 }
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04001357 if (i.ifFalse() && i.ifFalse()->isEmpty()) {
Ethan Nicholascb670962017-04-20 19:31:52 -04001358 // else block doesn't do anything, remove it
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04001359 i.ifFalse().reset();
Ethan Nicholascb670962017-04-20 19:31:52 -04001360 *outUpdated = true;
1361 *outNeedsRescan = true;
1362 }
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04001363 if (!i.ifFalse() && i.ifTrue()->isEmpty()) {
Ethan Nicholascb670962017-04-20 19:31:52 -04001364 // if block doesn't do anything, no else block
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04001365 if (i.test()->hasSideEffects()) {
Ethan Nicholascb670962017-04-20 19:31:52 -04001366 // test has side effects, keep it
1367 (*iter)->setStatement(std::unique_ptr<Statement>(
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04001368 new ExpressionStatement(std::move(i.test()))));
Ethan Nicholascb670962017-04-20 19:31:52 -04001369 } else {
1370 // no if, no else, no test side effects, kill the whole if
1371 // statement
1372 (*iter)->setStatement(std::unique_ptr<Statement>(new Nop()));
1373 }
1374 *outUpdated = true;
1375 *outNeedsRescan = true;
1376 }
1377 break;
1378 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001379 case Statement::Kind::kSwitch: {
John Stilesa5a97b42020-08-18 11:19:07 -04001380 SwitchStatement& s = stmt->as<SwitchStatement>();
Ethan Nicholas34b19c52020-09-14 11:33:47 -04001381 int64_t switchValue;
1382 if (fIRGenerator->getConstantInt(*s.fValue, &switchValue)) {
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001383 // switch is constant, replace it with the case that matches
1384 bool found = false;
1385 SwitchCase* defaultCase = nullptr;
John Stiles9d944232020-08-19 09:56:49 -04001386 for (const std::unique_ptr<SwitchCase>& c : s.fCases) {
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001387 if (!c->fValue) {
1388 defaultCase = c.get();
1389 continue;
1390 }
Ethan Nicholas34b19c52020-09-14 11:33:47 -04001391 int64_t caseValue;
1392 SkAssertResult(fIRGenerator->getConstantInt(*c->fValue, &caseValue));
1393 if (caseValue == switchValue) {
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001394 std::unique_ptr<Statement> newBlock = block_for_case(&s, c.get());
1395 if (newBlock) {
1396 (*iter)->setStatement(std::move(newBlock));
John Stiles9d944232020-08-19 09:56:49 -04001397 found = true;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001398 break;
1399 } else {
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -04001400 if (s.fIsStatic && !(fFlags & kPermitInvalidStaticTests_Flag)) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001401 this->error(s.fOffset,
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001402 "static switch contains non-static conditional break");
1403 s.fIsStatic = false;
1404 }
1405 return; // can't simplify
1406 }
1407 }
1408 }
1409 if (!found) {
1410 // no matching case. use default if it exists, or kill the whole thing
1411 if (defaultCase) {
1412 std::unique_ptr<Statement> newBlock = block_for_case(&s, defaultCase);
1413 if (newBlock) {
1414 (*iter)->setStatement(std::move(newBlock));
1415 } else {
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -04001416 if (s.fIsStatic && !(fFlags & kPermitInvalidStaticTests_Flag)) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001417 this->error(s.fOffset,
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001418 "static switch contains non-static conditional break");
1419 s.fIsStatic = false;
1420 }
1421 return; // can't simplify
1422 }
1423 } else {
1424 (*iter)->setStatement(std::unique_ptr<Statement>(new Nop()));
1425 }
1426 }
1427 *outUpdated = true;
1428 *outNeedsRescan = true;
1429 }
1430 break;
1431 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001432 case Statement::Kind::kExpression: {
John Stilesa5a97b42020-08-18 11:19:07 -04001433 ExpressionStatement& e = stmt->as<ExpressionStatement>();
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001434 SkASSERT((*iter)->statement()->get() == &e);
Ethan Nicholasd503a5a2020-09-30 09:29:55 -04001435 if (!e.expression()->hasSideEffects()) {
Ethan Nicholascb670962017-04-20 19:31:52 -04001436 // Expression statement with no side effects, kill it
Ethan Nicholasd503a5a2020-09-30 09:29:55 -04001437 if (!b.tryRemoveExpressionBefore(iter, e.expression().get())) {
Ethan Nicholascb670962017-04-20 19:31:52 -04001438 *outNeedsRescan = true;
1439 }
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001440 SkASSERT((*iter)->statement()->get() == stmt);
Ethan Nicholascb670962017-04-20 19:31:52 -04001441 (*iter)->setStatement(std::unique_ptr<Statement>(new Nop()));
1442 *outUpdated = true;
1443 }
1444 break;
1445 }
1446 default:
1447 break;
1448 }
1449}
1450
John Stiles0cc193a2020-09-09 09:39:34 -04001451bool Compiler::scanCFG(FunctionDefinition& f) {
1452 bool madeChanges = false;
1453
Ethan Nicholascb670962017-04-20 19:31:52 -04001454 CFG cfg = CFGGenerator().getCFG(f);
1455 this->computeDataFlow(&cfg);
ethannicholas22f939e2016-10-13 13:25:34 -07001456
1457 // check for unreachable code
1458 for (size_t i = 0; i < cfg.fBlocks.size(); i++) {
John Stiles0cc193a2020-09-09 09:39:34 -04001459 const BasicBlock& block = cfg.fBlocks[i];
John Stiles61e75e32020-10-01 15:42:37 -04001460 if (i != cfg.fStart && !block.fIsReachable && block.fNodes.size()) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001461 int offset;
John Stiles0cc193a2020-09-09 09:39:34 -04001462 const BasicBlock::Node& node = block.fNodes[0];
John Stiles70025e52020-09-28 16:08:58 -04001463 if (node.isStatement()) {
1464 offset = (*node.statement())->fOffset;
1465 } else {
1466 offset = (*node.expression())->fOffset;
1467 if ((*node.expression())->is<BoolLiteral>()) {
1468 // Function inlining can generate do { ... } while(false) loops which always
1469 // break, so the boolean condition is considered unreachable. Since not being
1470 // able to reach a literal is a non-issue in the first place, we don't report an
1471 // error in this case.
1472 continue;
1473 }
Ethan Nicholas86a43402017-01-19 13:32:00 -05001474 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001475 this->error(offset, String("unreachable"));
ethannicholas22f939e2016-10-13 13:25:34 -07001476 }
1477 }
1478 if (fErrorCount) {
John Stiles0cc193a2020-09-09 09:39:34 -04001479 return madeChanges;
ethannicholas22f939e2016-10-13 13:25:34 -07001480 }
1481
Ethan Nicholascb670962017-04-20 19:31:52 -04001482 // check for dead code & undefined variables, perform constant propagation
1483 std::unordered_set<const Variable*> undefinedVariables;
1484 bool updated;
1485 bool needsRescan = false;
1486 do {
1487 if (needsRescan) {
1488 cfg = CFGGenerator().getCFG(f);
1489 this->computeDataFlow(&cfg);
1490 needsRescan = false;
Ethan Nicholas113628d2017-02-02 16:11:39 -05001491 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001492
1493 updated = false;
Ethan Nicholas1de14812020-06-19 15:32:49 -04001494 bool first = true;
Ethan Nicholascb670962017-04-20 19:31:52 -04001495 for (BasicBlock& b : cfg.fBlocks) {
John Stiles61e75e32020-10-01 15:42:37 -04001496 if (!first && !b.fIsReachable) {
Ethan Nicholas1de14812020-06-19 15:32:49 -04001497 // Block was reachable before optimization, but has since become unreachable. In
1498 // addition to being dead code, it's broken - since control flow can't reach it, no
1499 // prior variable definitions can reach it, and therefore variables might look to
Brian Osmanc0213602020-10-06 14:43:32 -04001500 // have not been properly assigned. Kill it by replacing all statements with Nops.
Ethan Nicholas1de14812020-06-19 15:32:49 -04001501 for (BasicBlock::Node& node : b.fNodes) {
John Stiles70025e52020-09-28 16:08:58 -04001502 if (node.isStatement() && !(*node.statement())->is<Nop>()) {
John Stiles0cc193a2020-09-09 09:39:34 -04001503 node.setStatement(std::make_unique<Nop>());
1504 madeChanges = true;
Ethan Nicholas1de14812020-06-19 15:32:49 -04001505 }
1506 }
1507 continue;
1508 }
1509 first = false;
Ethan Nicholascb670962017-04-20 19:31:52 -04001510 DefinitionMap definitions = b.fBefore;
1511
1512 for (auto iter = b.fNodes.begin(); iter != b.fNodes.end() && !needsRescan; ++iter) {
John Stiles70025e52020-09-28 16:08:58 -04001513 if (iter->isExpression()) {
Ethan Nicholascb670962017-04-20 19:31:52 -04001514 this->simplifyExpression(definitions, b, &iter, &undefinedVariables, &updated,
1515 &needsRescan);
1516 } else {
1517 this->simplifyStatement(definitions, b, &iter, &undefinedVariables, &updated,
John Stiles0cc193a2020-09-09 09:39:34 -04001518 &needsRescan);
Ethan Nicholascb670962017-04-20 19:31:52 -04001519 }
Ethan Nicholas4b330df2017-05-17 10:52:55 -04001520 if (needsRescan) {
1521 break;
1522 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001523 this->addDefinitions(*iter, &definitions);
1524 }
Brian Osman01a3eb42020-09-14 11:32:49 -04001525
1526 if (needsRescan) {
1527 break;
1528 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001529 }
John Stiles0cc193a2020-09-09 09:39:34 -04001530 madeChanges |= updated;
Ethan Nicholascb670962017-04-20 19:31:52 -04001531 } while (updated);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001532 SkASSERT(!needsRescan);
ethannicholas22f939e2016-10-13 13:25:34 -07001533
Ethan Nicholas91a10532017-06-22 11:24:38 -04001534 // verify static ifs & switches, clean up dead variable decls
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001535 for (BasicBlock& b : cfg.fBlocks) {
1536 DefinitionMap definitions = b.fBefore;
1537
Ethan Nicholas91a10532017-06-22 11:24:38 -04001538 for (auto iter = b.fNodes.begin(); iter != b.fNodes.end() && !needsRescan;) {
John Stiles70025e52020-09-28 16:08:58 -04001539 if (iter->isStatement()) {
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001540 const Statement& s = **iter->statement();
Ethan Nicholase6592142020-09-08 10:22:09 -04001541 switch (s.kind()) {
1542 case Statement::Kind::kIf:
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04001543 if (s.as<IfStatement>().isStatic() &&
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -04001544 !(fFlags & kPermitInvalidStaticTests_Flag)) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001545 this->error(s.fOffset, "static if has non-static test");
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001546 }
Ethan Nicholas91a10532017-06-22 11:24:38 -04001547 ++iter;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001548 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001549 case Statement::Kind::kSwitch:
John Stilesa5a97b42020-08-18 11:19:07 -04001550 if (s.as<SwitchStatement>().fIsStatic &&
John Stiles0cc193a2020-09-09 09:39:34 -04001551 !(fFlags & kPermitInvalidStaticTests_Flag)) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001552 this->error(s.fOffset, "static switch has non-static test");
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001553 }
Ethan Nicholas91a10532017-06-22 11:24:38 -04001554 ++iter;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001555 break;
1556 default:
Ethan Nicholas91a10532017-06-22 11:24:38 -04001557 ++iter;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001558 break;
1559 }
Ethan Nicholas91a10532017-06-22 11:24:38 -04001560 } else {
1561 ++iter;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001562 }
1563 }
1564 }
1565
ethannicholas22f939e2016-10-13 13:25:34 -07001566 // check for missing return
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001567 if (f.fDeclaration.fReturnType != *fContext->fVoid_Type) {
John Stiles61e75e32020-10-01 15:42:37 -04001568 if (cfg.fBlocks[cfg.fExit].fIsReachable) {
Ethan Nicholase2c49992020-10-05 11:49:11 -04001569 this->error(f.fOffset, String("function '" + String(f.fDeclaration.name()) +
Ethan Nicholasdb80f692019-11-22 14:06:12 -05001570 "' can exit without returning a value"));
ethannicholas22f939e2016-10-13 13:25:34 -07001571 }
1572 }
John Stiles0cc193a2020-09-09 09:39:34 -04001573
1574 return madeChanges;
ethannicholas22f939e2016-10-13 13:25:34 -07001575}
1576
Brian Osman32d53552020-09-23 13:55:20 -04001577std::unique_ptr<Program> Compiler::convertProgram(
1578 Program::Kind kind,
1579 String text,
1580 const Program::Settings& settings,
1581 const std::vector<std::unique_ptr<ExternalValue>>* externalValues) {
1582 SkASSERT(!externalValues || (kind == Program::kGeneric_Kind));
Ethan Nicholas91164d12019-05-15 15:29:54 -04001583
ethannicholasb3058bd2016-07-01 08:22:01 -07001584 fErrorText = "";
1585 fErrorCount = 0;
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001586 fInliner.reset(&fIRGenerator->fContext, fIRGenerator->fModifiers.get(), &settings);
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001587 std::vector<std::unique_ptr<ProgramElement>>* inherited;
ethannicholasd598f792016-07-25 10:08:54 -07001588 std::vector<std::unique_ptr<ProgramElement>> elements;
ethannicholasb3058bd2016-07-01 08:22:01 -07001589 switch (kind) {
1590 case Program::kVertex_Kind:
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001591 inherited = &fVertexInclude;
John Stiles810c8cf2020-08-26 19:46:27 -04001592 fIRGenerator->fIntrinsics = fGPUIntrinsics.get();
Brian Osmane498b3c2020-09-23 14:42:11 -04001593 fIRGenerator->start(&settings, fVertexSymbolTable, inherited);
ethannicholasb3058bd2016-07-01 08:22:01 -07001594 break;
1595 case Program::kFragment_Kind:
Brian Osman00a8b5b2020-10-02 09:06:04 -04001596 inherited = nullptr;
1597 fIRGenerator->fIntrinsics = fFragmentIntrinsics.get();
1598 fIRGenerator->start(&settings, fFragmentSymbolTable, /*inherited=*/nullptr);
ethannicholasb3058bd2016-07-01 08:22:01 -07001599 break;
Ethan Nicholas52cad152017-02-16 16:37:32 -05001600 case Program::kGeometry_Kind:
Ethan Nicholasc18bb512020-07-28 14:46:53 -04001601 this->loadGeometryIntrinsics();
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001602 inherited = &fGeometryInclude;
John Stiles810c8cf2020-08-26 19:46:27 -04001603 fIRGenerator->fIntrinsics = fGPUIntrinsics.get();
Brian Osmane498b3c2020-09-23 14:42:11 -04001604 fIRGenerator->start(&settings, fGeometrySymbolTable, inherited);
Ethan Nicholas52cad152017-02-16 16:37:32 -05001605 break;
Brian Osman8e2ef022020-09-30 13:26:43 -04001606 case Program::kFragmentProcessor_Kind:
1607 this->loadFPIntrinsics();
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001608 inherited = nullptr;
Brian Osman8e2ef022020-09-30 13:26:43 -04001609 fIRGenerator->fIntrinsics = fFPIntrinsics.get();
1610 fIRGenerator->start(&settings, fFPSymbolTable, /*inherited=*/nullptr);
Ethan Nicholas762466e2017-06-29 10:03:38 -04001611 break;
Ethan Nicholas8da1e652019-05-24 11:01:59 -04001612 case Program::kPipelineStage_Kind:
Ethan Nicholasc18bb512020-07-28 14:46:53 -04001613 this->loadPipelineIntrinsics();
Brian Osman8e2ef022020-09-30 13:26:43 -04001614 inherited = nullptr;
1615 fIRGenerator->fIntrinsics = fPipelineIntrinsics.get();
1616 fIRGenerator->start(&settings, fPipelineSymbolTable, /*inherited=*/nullptr);
Ethan Nicholas8da1e652019-05-24 11:01:59 -04001617 break;
Ethan Nicholas746035a2019-04-23 13:31:09 -04001618 case Program::kGeneric_Kind:
Ethan Nicholasc18bb512020-07-28 14:46:53 -04001619 this->loadInterpreterIntrinsics();
Brian Osmaneac49832020-09-18 11:49:22 -04001620 inherited = nullptr;
John Stiles810c8cf2020-08-26 19:46:27 -04001621 fIRGenerator->fIntrinsics = fInterpreterIntrinsics.get();
Brian Osmane498b3c2020-09-23 14:42:11 -04001622 fIRGenerator->start(&settings, fInterpreterSymbolTable, /*inherited=*/nullptr);
Ethan Nicholas0d997662019-04-08 09:46:01 -04001623 break;
ethannicholasb3058bd2016-07-01 08:22:01 -07001624 }
Brian Osman32d53552020-09-23 13:55:20 -04001625 if (externalValues) {
1626 // Add any external values to the symbol table. IRGenerator::start() has pushed a table, so
1627 // we're only making these visible to the current Program.
1628 for (const auto& ev : *externalValues) {
John Stilesb8cc6652020-10-08 09:12:07 -04001629 fIRGenerator->fSymbolTable->addWithoutOwnership(ev.get());
Brian Osman32d53552020-09-23 13:55:20 -04001630 }
1631 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001632 std::unique_ptr<String> textPtr(new String(std::move(text)));
1633 fSource = textPtr.get();
Ethan Nicholasc18bb512020-07-28 14:46:53 -04001634 fIRGenerator->convertProgram(kind, textPtr->c_str(), textPtr->size(), &elements);
John Stilesfbd050b2020-08-03 13:21:46 -04001635 auto result = std::make_unique<Program>(kind,
1636 std::move(textPtr),
1637 settings,
1638 fContext,
1639 inherited,
1640 std::move(elements),
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001641 fIRGenerator->releaseModifiers(),
John Stilesfbd050b2020-08-03 13:21:46 -04001642 fIRGenerator->fSymbolTable,
1643 fIRGenerator->fInputs);
Brian Osmane498b3c2020-09-23 14:42:11 -04001644 fIRGenerator->finish();
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001645 if (fErrorCount) {
1646 return nullptr;
1647 }
Ethan Nicholas34b19c52020-09-14 11:33:47 -04001648 if (settings.fOptimize && !this->optimize(*result)) {
1649 return nullptr;
1650 }
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001651 return result;
1652}
1653
Ethan Nicholas00543112018-07-31 09:44:36 -04001654bool Compiler::optimize(Program& program) {
1655 SkASSERT(!fErrorCount);
Ethan Nicholas34b19c52020-09-14 11:33:47 -04001656 fIRGenerator->fKind = program.fKind;
1657 fIRGenerator->fSettings = &program.fSettings;
John Stiles7954d6c2020-09-01 10:53:02 -04001658
Ethan Nicholas34b19c52020-09-14 11:33:47 -04001659 while (fErrorCount == 0) {
1660 bool madeChanges = false;
John Stiles7954d6c2020-09-01 10:53:02 -04001661
Ethan Nicholas34b19c52020-09-14 11:33:47 -04001662 // Scan and optimize based on the control-flow graph for each function.
1663 for (ProgramElement& element : program) {
1664 if (element.is<FunctionDefinition>()) {
1665 madeChanges |= this->scanCFG(element.as<FunctionDefinition>());
1666 }
1667 }
1668
1669 // Perform inline-candidate analysis and inline any functions deemed suitable.
John Stiles881a10c2020-09-19 10:13:24 -04001670 madeChanges |= fInliner.analyze(program);
Ethan Nicholas34b19c52020-09-14 11:33:47 -04001671
1672 // Remove dead functions. We wait until after analysis so that we still report errors,
1673 // even in unused code.
1674 if (program.fSettings.fRemoveDeadFunctions) {
1675 program.fElements.erase(
1676 std::remove_if(program.fElements.begin(),
1677 program.fElements.end(),
1678 [&](const std::unique_ptr<ProgramElement>& element) {
1679 if (!element->is<FunctionDefinition>()) {
1680 return false;
1681 }
1682 const auto& fn = element->as<FunctionDefinition>();
1683 bool dead = fn.fDeclaration.fCallCount == 0 &&
Ethan Nicholase2c49992020-10-05 11:49:11 -04001684 fn.fDeclaration.name() != "main";
Ethan Nicholas34b19c52020-09-14 11:33:47 -04001685 madeChanges |= dead;
1686 return dead;
1687 }),
1688 program.fElements.end());
1689 }
1690
1691 if (program.fKind != Program::kFragmentProcessor_Kind) {
Brian Osmanc0213602020-10-06 14:43:32 -04001692 // Remove declarations of dead global variables
Ethan Nicholas34b19c52020-09-14 11:33:47 -04001693 program.fElements.erase(
1694 std::remove_if(program.fElements.begin(), program.fElements.end(),
1695 [&](const std::unique_ptr<ProgramElement>& element) {
Brian Osmanc0213602020-10-06 14:43:32 -04001696 if (!element->is<GlobalVarDeclaration>()) {
Ethan Nicholas34b19c52020-09-14 11:33:47 -04001697 return false;
1698 }
Brian Osmanc0213602020-10-06 14:43:32 -04001699 const auto& varDecl = element->as<GlobalVarDeclaration>();
1700 bool dead = varDecl.fDecl->fVar->dead();
Ethan Nicholas34b19c52020-09-14 11:33:47 -04001701 madeChanges |= dead;
1702 return dead;
1703 }),
1704 program.fElements.end());
1705 }
John Stiles73a6bff2020-09-09 13:40:37 -04001706
Ethan Nicholas34b19c52020-09-14 11:33:47 -04001707 if (!madeChanges) {
1708 break;
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001709 }
Ethan Nicholas00543112018-07-31 09:44:36 -04001710 }
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001711 program.finish();
Ethan Nicholas00543112018-07-31 09:44:36 -04001712 return fErrorCount == 0;
1713}
1714
Brian Osmanfb32ddf2019-06-18 10:14:20 -04001715#if defined(SKSL_STANDALONE) || SK_SUPPORT_GPU
1716
Ethan Nicholas00543112018-07-31 09:44:36 -04001717bool Compiler::toSPIRV(Program& program, OutputStream& out) {
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001718#ifdef SK_ENABLE_SPIRV_VALIDATION
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001719 StringStream buffer;
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001720 fSource = program.fSource.get();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001721 SPIRVCodeGenerator cg(&fIRGenerator->fContext, fIRGenerator->fModifiers.get(), &program, this,
1722 &buffer);
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001723 bool result = cg.generateCode();
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001724 fSource = nullptr;
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001725 if (result) {
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001726 spvtools::SpirvTools tools(SPV_ENV_VULKAN_1_0);
Ethan Nicholas762466e2017-06-29 10:03:38 -04001727 const String& data = buffer.str();
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001728 SkASSERT(0 == data.size() % 4);
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001729 auto dumpmsg = [](spv_message_level_t, const char*, const spv_position_t&, const char* m) {
1730 SkDebugf("SPIR-V validation error: %s\n", m);
1731 };
1732 tools.SetMessageConsumer(dumpmsg);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001733 // Verify that the SPIR-V we produced is valid. If this SkASSERT fails, check the logs prior
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001734 // to the failure to see the validation errors.
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001735 SkAssertResult(tools.Validate((const uint32_t*) data.c_str(), data.size() / 4));
Ethan Nicholas762466e2017-06-29 10:03:38 -04001736 out.write(data.c_str(), data.size());
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001737 }
1738#else
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001739 fSource = program.fSource.get();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001740 SPIRVCodeGenerator cg(&fIRGenerator->fContext, fIRGenerator->fModifiers.get(), &program, this,
1741 &out);
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001742 bool result = cg.generateCode();
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001743 fSource = nullptr;
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001744#endif
Ethan Nicholasce33f102016-12-09 17:22:59 -05001745 return result;
1746}
1747
Ethan Nicholas00543112018-07-31 09:44:36 -04001748bool Compiler::toSPIRV(Program& program, String* out) {
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001749 StringStream buffer;
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001750 bool result = this->toSPIRV(program, buffer);
1751 if (result) {
Ethan Nicholas762466e2017-06-29 10:03:38 -04001752 *out = buffer.str();
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001753 }
1754 return result;
1755}
1756
Ethan Nicholas00543112018-07-31 09:44:36 -04001757bool Compiler::toGLSL(Program& program, OutputStream& out) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001758 fSource = program.fSource.get();
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001759 GLSLCodeGenerator cg(fContext.get(), &program, this, &out);
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001760 bool result = cg.generateCode();
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001761 fSource = nullptr;
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001762 return result;
1763}
1764
Ethan Nicholas00543112018-07-31 09:44:36 -04001765bool Compiler::toGLSL(Program& program, String* out) {
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001766 StringStream buffer;
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001767 bool result = this->toGLSL(program, buffer);
1768 if (result) {
Ethan Nicholas762466e2017-06-29 10:03:38 -04001769 *out = buffer.str();
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001770 }
1771 return result;
1772}
1773
Brian Osmanc0243912020-02-19 15:35:26 -05001774bool Compiler::toHLSL(Program& program, String* out) {
1775 String spirv;
1776 if (!this->toSPIRV(program, &spirv)) {
1777 return false;
1778 }
1779
1780 return SPIRVtoHLSL(spirv, out);
1781}
1782
Ethan Nicholas00543112018-07-31 09:44:36 -04001783bool Compiler::toMetal(Program& program, OutputStream& out) {
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001784 MetalCodeGenerator cg(fContext.get(), &program, this, &out);
Ethan Nicholascc305772017-10-13 16:17:45 -04001785 bool result = cg.generateCode();
Ethan Nicholascc305772017-10-13 16:17:45 -04001786 return result;
1787}
1788
Ethan Nicholas00543112018-07-31 09:44:36 -04001789bool Compiler::toMetal(Program& program, String* out) {
Timothy Liangb8eeb802018-07-23 16:46:16 -04001790 StringStream buffer;
1791 bool result = this->toMetal(program, buffer);
1792 if (result) {
1793 *out = buffer.str();
1794 }
1795 return result;
1796}
1797
Greg Daniela28ea672020-09-25 11:12:56 -04001798#if defined(SKSL_STANDALONE) || GR_TEST_UTILS
Ethan Nicholas00543112018-07-31 09:44:36 -04001799bool Compiler::toCPP(Program& program, String name, OutputStream& out) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001800 fSource = program.fSource.get();
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001801 CPPCodeGenerator cg(fContext.get(), &program, this, name, &out);
Ethan Nicholas762466e2017-06-29 10:03:38 -04001802 bool result = cg.generateCode();
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001803 fSource = nullptr;
Ethan Nicholas762466e2017-06-29 10:03:38 -04001804 return result;
1805}
1806
Ethan Nicholas00543112018-07-31 09:44:36 -04001807bool Compiler::toH(Program& program, String name, OutputStream& out) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001808 fSource = program.fSource.get();
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001809 HCodeGenerator cg(fContext.get(), &program, this, name, &out);
Ethan Nicholas762466e2017-06-29 10:03:38 -04001810 bool result = cg.generateCode();
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001811 fSource = nullptr;
Ethan Nicholas00543112018-07-31 09:44:36 -04001812 return result;
1813}
Greg Daniela28ea672020-09-25 11:12:56 -04001814#endif // defined(SKSL_STANDALONE) || GR_TEST_UTILS
Ethan Nicholas00543112018-07-31 09:44:36 -04001815
Ethan Nicholas2a479a52020-08-18 16:29:45 -04001816#endif // defined(SKSL_STANDALONE) || SK_SUPPORT_GPU
Brian Osman2e29ab52019-09-20 12:19:11 -04001817
1818#if !defined(SKSL_STANDALONE) && SK_SUPPORT_GPU
Brian Osmana4b91692020-08-10 14:26:16 -04001819bool Compiler::toPipelineStage(Program& program, PipelineStageArgs* outArgs) {
Ethan Nicholas00543112018-07-31 09:44:36 -04001820 fSource = program.fSource.get();
1821 StringStream buffer;
Brian Osman300fe1d2020-01-23 15:42:43 -05001822 PipelineStageCodeGenerator cg(fContext.get(), &program, this, &buffer, outArgs);
Ethan Nicholas00543112018-07-31 09:44:36 -04001823 bool result = cg.generateCode();
1824 fSource = nullptr;
1825 if (result) {
Brian Osman107c6662019-12-30 15:02:30 -05001826 outArgs->fCode = buffer.str();
Ethan Nicholas00543112018-07-31 09:44:36 -04001827 }
Ethan Nicholas762466e2017-06-29 10:03:38 -04001828 return result;
1829}
Brian Osmanfb32ddf2019-06-18 10:14:20 -04001830#endif
1831
Ethan Nicholas0e9401d2019-03-21 11:05:37 -04001832std::unique_ptr<ByteCode> Compiler::toByteCode(Program& program) {
Mike Klein853d4ed2020-08-20 00:41:00 +00001833#if defined(SK_ENABLE_SKSL_INTERPRETER)
Brian Osman808f0212020-01-21 15:36:47 -05001834 fSource = program.fSource.get();
Ethan Nicholas0e9401d2019-03-21 11:05:37 -04001835 std::unique_ptr<ByteCode> result(new ByteCode());
Brian Osmanb08cc022020-04-02 11:38:40 -04001836 ByteCodeGenerator cg(fContext.get(), &program, this, result.get());
1837 bool success = cg.generateCode();
1838 fSource = nullptr;
1839 if (success) {
Ethan Nicholas0e9401d2019-03-21 11:05:37 -04001840 return result;
1841 }
Mike Klein853d4ed2020-08-20 00:41:00 +00001842#else
1843 ABORT("ByteCode interpreter not enabled");
1844#endif
Ethan Nicholas0e9401d2019-03-21 11:05:37 -04001845 return nullptr;
1846}
1847
Brian Osman401a0092020-09-10 14:47:24 -04001848const char* Compiler::OperatorName(Token::Kind op) {
1849 switch (op) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001850 case Token::Kind::TK_PLUS: return "+";
1851 case Token::Kind::TK_MINUS: return "-";
1852 case Token::Kind::TK_STAR: return "*";
1853 case Token::Kind::TK_SLASH: return "/";
1854 case Token::Kind::TK_PERCENT: return "%";
1855 case Token::Kind::TK_SHL: return "<<";
1856 case Token::Kind::TK_SHR: return ">>";
1857 case Token::Kind::TK_LOGICALNOT: return "!";
1858 case Token::Kind::TK_LOGICALAND: return "&&";
1859 case Token::Kind::TK_LOGICALOR: return "||";
1860 case Token::Kind::TK_LOGICALXOR: return "^^";
1861 case Token::Kind::TK_BITWISENOT: return "~";
1862 case Token::Kind::TK_BITWISEAND: return "&";
1863 case Token::Kind::TK_BITWISEOR: return "|";
1864 case Token::Kind::TK_BITWISEXOR: return "^";
1865 case Token::Kind::TK_EQ: return "=";
1866 case Token::Kind::TK_EQEQ: return "==";
1867 case Token::Kind::TK_NEQ: return "!=";
1868 case Token::Kind::TK_LT: return "<";
1869 case Token::Kind::TK_GT: return ">";
1870 case Token::Kind::TK_LTEQ: return "<=";
1871 case Token::Kind::TK_GTEQ: return ">=";
1872 case Token::Kind::TK_PLUSEQ: return "+=";
1873 case Token::Kind::TK_MINUSEQ: return "-=";
1874 case Token::Kind::TK_STAREQ: return "*=";
1875 case Token::Kind::TK_SLASHEQ: return "/=";
1876 case Token::Kind::TK_PERCENTEQ: return "%=";
1877 case Token::Kind::TK_SHLEQ: return "<<=";
1878 case Token::Kind::TK_SHREQ: return ">>=";
1879 case Token::Kind::TK_LOGICALANDEQ: return "&&=";
1880 case Token::Kind::TK_LOGICALOREQ: return "||=";
1881 case Token::Kind::TK_LOGICALXOREQ: return "^^=";
1882 case Token::Kind::TK_BITWISEANDEQ: return "&=";
1883 case Token::Kind::TK_BITWISEOREQ: return "|=";
1884 case Token::Kind::TK_BITWISEXOREQ: return "^=";
1885 case Token::Kind::TK_PLUSPLUS: return "++";
1886 case Token::Kind::TK_MINUSMINUS: return "--";
1887 case Token::Kind::TK_COMMA: return ",";
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001888 default:
Brian Osman401a0092020-09-10 14:47:24 -04001889 ABORT("unsupported operator: %d\n", (int) op);
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001890 }
1891}
1892
1893
1894bool Compiler::IsAssignment(Token::Kind op) {
1895 switch (op) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001896 case Token::Kind::TK_EQ: // fall through
1897 case Token::Kind::TK_PLUSEQ: // fall through
1898 case Token::Kind::TK_MINUSEQ: // fall through
1899 case Token::Kind::TK_STAREQ: // fall through
1900 case Token::Kind::TK_SLASHEQ: // fall through
1901 case Token::Kind::TK_PERCENTEQ: // fall through
1902 case Token::Kind::TK_SHLEQ: // fall through
1903 case Token::Kind::TK_SHREQ: // fall through
1904 case Token::Kind::TK_BITWISEOREQ: // fall through
1905 case Token::Kind::TK_BITWISEXOREQ: // fall through
1906 case Token::Kind::TK_BITWISEANDEQ: // fall through
1907 case Token::Kind::TK_LOGICALOREQ: // fall through
1908 case Token::Kind::TK_LOGICALXOREQ: // fall through
1909 case Token::Kind::TK_LOGICALANDEQ:
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001910 return true;
1911 default:
1912 return false;
1913 }
1914}
1915
Brian Osman401a0092020-09-10 14:47:24 -04001916Token::Kind Compiler::RemoveAssignment(Token::Kind op) {
1917 switch (op) {
1918 case Token::Kind::TK_PLUSEQ: return Token::Kind::TK_PLUS;
1919 case Token::Kind::TK_MINUSEQ: return Token::Kind::TK_MINUS;
1920 case Token::Kind::TK_STAREQ: return Token::Kind::TK_STAR;
1921 case Token::Kind::TK_SLASHEQ: return Token::Kind::TK_SLASH;
1922 case Token::Kind::TK_PERCENTEQ: return Token::Kind::TK_PERCENT;
1923 case Token::Kind::TK_SHLEQ: return Token::Kind::TK_SHL;
1924 case Token::Kind::TK_SHREQ: return Token::Kind::TK_SHR;
1925 case Token::Kind::TK_BITWISEOREQ: return Token::Kind::TK_BITWISEOR;
1926 case Token::Kind::TK_BITWISEXOREQ: return Token::Kind::TK_BITWISEXOR;
1927 case Token::Kind::TK_BITWISEANDEQ: return Token::Kind::TK_BITWISEAND;
1928 case Token::Kind::TK_LOGICALOREQ: return Token::Kind::TK_LOGICALOR;
1929 case Token::Kind::TK_LOGICALXOREQ: return Token::Kind::TK_LOGICALXOR;
1930 case Token::Kind::TK_LOGICALANDEQ: return Token::Kind::TK_LOGICALAND;
1931 default: return op;
1932 }
1933}
1934
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001935Position Compiler::position(int offset) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001936 SkASSERT(fSource);
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001937 int line = 1;
1938 int column = 1;
1939 for (int i = 0; i < offset; i++) {
1940 if ((*fSource)[i] == '\n') {
1941 ++line;
1942 column = 1;
1943 }
1944 else {
1945 ++column;
1946 }
1947 }
1948 return Position(line, column);
1949}
1950
1951void Compiler::error(int offset, String msg) {
ethannicholasb3058bd2016-07-01 08:22:01 -07001952 fErrorCount++;
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001953 Position pos = this->position(offset);
1954 fErrorText += "error: " + to_string(pos.fLine) + ": " + msg.c_str() + "\n";
ethannicholasb3058bd2016-07-01 08:22:01 -07001955}
1956
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001957String Compiler::errorText() {
Ethan Nicholas00543112018-07-31 09:44:36 -04001958 this->writeErrorCount();
1959 fErrorCount = 0;
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001960 String result = fErrorText;
ethannicholasb3058bd2016-07-01 08:22:01 -07001961 return result;
1962}
1963
1964void Compiler::writeErrorCount() {
1965 if (fErrorCount) {
1966 fErrorText += to_string(fErrorCount) + " error";
1967 if (fErrorCount > 1) {
1968 fErrorText += "s";
1969 }
1970 fErrorText += "\n";
1971 }
1972}
1973
John Stilesa6841be2020-08-06 14:11:56 -04001974} // namespace SkSL