blob: 05889e678eace785f27707202006242944247911 [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 Osmanafa18ee2020-10-07 17:47:45 -040076 for (std::unique_ptr<ProgramElement>& element : *src) {
Ethan Nicholase6592142020-09-08 10:22:09 -040077 switch (element->kind()) {
78 case ProgramElement::Kind::kFunction: {
Brian Osmanafa18ee2020-10-07 17:47:45 -040079 const FunctionDefinition& f = element->as<FunctionDefinition>();
Brian Osman08f986d2020-05-13 17:06:46 -040080 SkASSERT(f.fDeclaration.fBuiltin);
Brian Osman2b469eb2020-09-21 11:32:10 -040081 target->insertOrDie(f.fDeclaration.description(), std::move(element));
Ethan Nicholasdb80f692019-11-22 14:06:12 -050082 break;
83 }
Ethan Nicholase6592142020-09-08 10:22:09 -040084 case ProgramElement::Kind::kEnum: {
Brian Osmanafa18ee2020-10-07 17:47:45 -040085 const Enum& e = element->as<Enum>();
86 SkASSERT(e.isBuiltin());
Ethan Nicholasd83ded82020-09-29 17:05:54 -040087 target->insertOrDie(e.typeName(), std::move(element));
Ethan Nicholasdb80f692019-11-22 14:06:12 -050088 break;
89 }
Brian Osmanc0213602020-10-06 14:43:32 -040090 case ProgramElement::Kind::kGlobalVar: {
Brian Osmanafa18ee2020-10-07 17:47:45 -040091 const Variable* var = element->as<GlobalVarDeclaration>().fDecl->fVar;
92 SkASSERT(var->isBuiltin());
Ethan Nicholase2c49992020-10-05 11:49:11 -040093 target->insertOrDie(var->name(), std::move(element));
Brian Osmanafa18ee2020-10-07 17:47:45 -040094 break;
95 }
96 case ProgramElement::Kind::kInterfaceBlock: {
97 const Variable* var = element->as<InterfaceBlock>().fVariable;
98 SkASSERT(var->isBuiltin());
99 target->insertOrDie(var->name(), std::move(element));
Brian Osman8e2ef022020-09-30 13:26:43 -0400100 break;
101 }
Ethan Nicholasdb80f692019-11-22 14:06:12 -0500102 default:
Brian Osman00a8b5b2020-10-02 09:06:04 -0400103 printf("Unsupported element: %s\n", element->description().c_str());
104 SkASSERT(false);
Brian Osman2b469eb2020-09-21 11:32:10 -0400105 break;
Ethan Nicholasdb80f692019-11-22 14:06:12 -0500106 }
107 }
108}
109
John Stilesbc0c29e2020-09-28 13:13:40 -0400110static void reset_call_counts(std::vector<std::unique_ptr<ProgramElement>>* src) {
111 for (std::unique_ptr<ProgramElement>& element : *src) {
112 if (element->is<FunctionDefinition>()) {
113 const FunctionDeclaration& fnDecl = element->as<FunctionDefinition>().fDeclaration;
114 fnDecl.fCallCount = 0;
115 }
116 }
117}
118
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -0400119Compiler::Compiler(Flags flags)
Brian Osman00a8b5b2020-10-02 09:06:04 -0400120: fFlags(flags)
John Stiles810c8cf2020-08-26 19:46:27 -0400121, fContext(std::make_shared<Context>())
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -0400122, fErrorCount(0) {
Brian Osmaneac49832020-09-18 11:49:22 -0400123 fRootSymbolTable = std::make_shared<SymbolTable>(this);
John Stiles941fc712020-09-19 12:47:10 +0000124 fIRGenerator =
125 std::make_unique<IRGenerator>(fContext.get(), &fInliner, fRootSymbolTable, *this);
John Stilesb8cc6652020-10-08 09:12:07 -0400126 #define ADD_TYPE(t) fRootSymbolTable->addWithoutOwnership(fContext->f ## t ## _Type.get())
ethannicholasb3058bd2016-07-01 08:22:01 -0700127 ADD_TYPE(Void);
128 ADD_TYPE(Float);
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400129 ADD_TYPE(Float2);
130 ADD_TYPE(Float3);
131 ADD_TYPE(Float4);
Ethan Nicholasdcba08e2017-08-02 10:52:54 -0400132 ADD_TYPE(Half);
133 ADD_TYPE(Half2);
134 ADD_TYPE(Half3);
135 ADD_TYPE(Half4);
ethannicholasb3058bd2016-07-01 08:22:01 -0700136 ADD_TYPE(Int);
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400137 ADD_TYPE(Int2);
138 ADD_TYPE(Int3);
139 ADD_TYPE(Int4);
ethannicholasb3058bd2016-07-01 08:22:01 -0700140 ADD_TYPE(UInt);
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400141 ADD_TYPE(UInt2);
142 ADD_TYPE(UInt3);
143 ADD_TYPE(UInt4);
Ethan Nicholasdcba08e2017-08-02 10:52:54 -0400144 ADD_TYPE(Short);
145 ADD_TYPE(Short2);
146 ADD_TYPE(Short3);
147 ADD_TYPE(Short4);
148 ADD_TYPE(UShort);
149 ADD_TYPE(UShort2);
150 ADD_TYPE(UShort3);
151 ADD_TYPE(UShort4);
Ruiqi Maob609e6d2018-07-17 10:19:38 -0400152 ADD_TYPE(Byte);
153 ADD_TYPE(Byte2);
154 ADD_TYPE(Byte3);
155 ADD_TYPE(Byte4);
156 ADD_TYPE(UByte);
157 ADD_TYPE(UByte2);
158 ADD_TYPE(UByte3);
159 ADD_TYPE(UByte4);
ethannicholasb3058bd2016-07-01 08:22:01 -0700160 ADD_TYPE(Bool);
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400161 ADD_TYPE(Bool2);
162 ADD_TYPE(Bool3);
163 ADD_TYPE(Bool4);
164 ADD_TYPE(Float2x2);
165 ADD_TYPE(Float2x3);
166 ADD_TYPE(Float2x4);
167 ADD_TYPE(Float3x2);
168 ADD_TYPE(Float3x3);
169 ADD_TYPE(Float3x4);
170 ADD_TYPE(Float4x2);
171 ADD_TYPE(Float4x3);
172 ADD_TYPE(Float4x4);
Ethan Nicholasdcba08e2017-08-02 10:52:54 -0400173 ADD_TYPE(Half2x2);
174 ADD_TYPE(Half2x3);
175 ADD_TYPE(Half2x4);
176 ADD_TYPE(Half3x2);
177 ADD_TYPE(Half3x3);
178 ADD_TYPE(Half3x4);
179 ADD_TYPE(Half4x2);
180 ADD_TYPE(Half4x3);
181 ADD_TYPE(Half4x4);
ethannicholasb3058bd2016-07-01 08:22:01 -0700182 ADD_TYPE(GenType);
Ethan Nicholasdcba08e2017-08-02 10:52:54 -0400183 ADD_TYPE(GenHType);
ethannicholasb3058bd2016-07-01 08:22:01 -0700184 ADD_TYPE(GenIType);
185 ADD_TYPE(GenUType);
186 ADD_TYPE(GenBType);
187 ADD_TYPE(Mat);
188 ADD_TYPE(Vec);
189 ADD_TYPE(GVec);
190 ADD_TYPE(GVec2);
191 ADD_TYPE(GVec3);
192 ADD_TYPE(GVec4);
Ethan Nicholasdcba08e2017-08-02 10:52:54 -0400193 ADD_TYPE(HVec);
ethannicholasb3058bd2016-07-01 08:22:01 -0700194 ADD_TYPE(IVec);
195 ADD_TYPE(UVec);
Ethan Nicholasdcba08e2017-08-02 10:52:54 -0400196 ADD_TYPE(SVec);
197 ADD_TYPE(USVec);
Ruiqi Maob609e6d2018-07-17 10:19:38 -0400198 ADD_TYPE(ByteVec);
199 ADD_TYPE(UByteVec);
ethannicholasb3058bd2016-07-01 08:22:01 -0700200 ADD_TYPE(BVec);
201
202 ADD_TYPE(Sampler1D);
203 ADD_TYPE(Sampler2D);
204 ADD_TYPE(Sampler3D);
ethannicholas5961bc92016-10-12 06:39:56 -0700205 ADD_TYPE(SamplerExternalOES);
ethannicholasb3058bd2016-07-01 08:22:01 -0700206 ADD_TYPE(SamplerCube);
207 ADD_TYPE(Sampler2DRect);
208 ADD_TYPE(Sampler1DArray);
209 ADD_TYPE(Sampler2DArray);
210 ADD_TYPE(SamplerCubeArray);
211 ADD_TYPE(SamplerBuffer);
212 ADD_TYPE(Sampler2DMS);
213 ADD_TYPE(Sampler2DMSArray);
214
Brian Salomonbf7b6202016-11-11 16:08:03 -0500215 ADD_TYPE(ISampler2D);
216
Brian Salomon2a51de82016-11-16 12:06:01 -0500217 ADD_TYPE(Image2D);
218 ADD_TYPE(IImage2D);
219
Greg Daniel64773e62016-11-22 09:44:03 -0500220 ADD_TYPE(SubpassInput);
221 ADD_TYPE(SubpassInputMS);
222
ethannicholasb3058bd2016-07-01 08:22:01 -0700223 ADD_TYPE(GSampler1D);
224 ADD_TYPE(GSampler2D);
225 ADD_TYPE(GSampler3D);
226 ADD_TYPE(GSamplerCube);
227 ADD_TYPE(GSampler2DRect);
228 ADD_TYPE(GSampler1DArray);
229 ADD_TYPE(GSampler2DArray);
230 ADD_TYPE(GSamplerCubeArray);
231 ADD_TYPE(GSamplerBuffer);
232 ADD_TYPE(GSampler2DMS);
233 ADD_TYPE(GSampler2DMSArray);
234
235 ADD_TYPE(Sampler1DShadow);
236 ADD_TYPE(Sampler2DShadow);
237 ADD_TYPE(SamplerCubeShadow);
238 ADD_TYPE(Sampler2DRectShadow);
239 ADD_TYPE(Sampler1DArrayShadow);
240 ADD_TYPE(Sampler2DArrayShadow);
241 ADD_TYPE(SamplerCubeArrayShadow);
242 ADD_TYPE(GSampler2DArrayShadow);
243 ADD_TYPE(GSamplerCubeArrayShadow);
Ethan Nicholasc9472af2017-10-10 16:30:21 -0400244 ADD_TYPE(FragmentProcessor);
Stephen Whiteff5d7a22019-07-26 17:42:06 -0400245 ADD_TYPE(Sampler);
246 ADD_TYPE(Texture2D);
ethannicholasb3058bd2016-07-01 08:22:01 -0700247
Brian Osman28590d52020-03-23 16:59:08 -0400248 StringFragment fpAliasName("shader");
John Stiles49a547f2020-10-06 16:14:37 -0400249 fRootSymbolTable->addAlias(fpAliasName, fContext->fFragmentProcessor_Type.get());
Brian Osman28590d52020-03-23 16:59:08 -0400250
Brian Osman3887a012020-09-30 13:22:27 -0400251 // sk_Caps is "builtin", but all references to it are resolved to Settings, so we don't need to
252 // treat it as builtin (ie, no need to clone it into the Program).
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700253 StringFragment skCapsName("sk_Caps");
John Stilesb8cc6652020-10-08 09:12:07 -0400254 fRootSymbolTable->add(std::make_unique<Variable>(/*offset=*/-1,
Ethan Nicholas041fd0a2020-10-07 16:42:04 -0400255 fIRGenerator->fModifiers->handle(Modifiers()),
256 skCapsName, fContext->fSkCaps_Type.get(),
Brian Osman3887a012020-09-30 13:22:27 -0400257 /*builtin=*/false, Variable::kGlobal_Storage));
Ethan Nicholas3605ace2016-11-21 15:59:48 -0500258
Brian Osman00a8b5b2020-10-02 09:06:04 -0400259 fIRGenerator->fIntrinsics = nullptr;
260 std::vector<std::unique_ptr<ProgramElement>> gpuElements;
Brian Osmanafa18ee2020-10-07 17:47:45 -0400261 std::vector<std::unique_ptr<ProgramElement>> vertElements;
Brian Osman00a8b5b2020-10-02 09:06:04 -0400262 std::vector<std::unique_ptr<ProgramElement>> fragElements;
Brian Osmandd496172020-08-08 08:17:18 -0400263#if SKSL_STANDALONE
Brian Osmaneac49832020-09-18 11:49:22 -0400264 this->processIncludeFile(Program::kFragment_Kind, SKSL_GPU_INCLUDE, fRootSymbolTable,
Brian Osman00a8b5b2020-10-02 09:06:04 -0400265 &gpuElements, &fGpuSymbolTable);
Ethan Nicholasb33fa3f2020-08-06 13:00:19 -0400266 this->processIncludeFile(Program::kVertex_Kind, SKSL_VERT_INCLUDE, fGpuSymbolTable,
Brian Osmanafa18ee2020-10-07 17:47:45 -0400267 &vertElements, &fVertexSymbolTable);
Ethan Nicholasb33fa3f2020-08-06 13:00:19 -0400268 this->processIncludeFile(Program::kFragment_Kind, SKSL_FRAG_INCLUDE, fGpuSymbolTable,
Brian Osman00a8b5b2020-10-02 09:06:04 -0400269 &fragElements, &fFragmentSymbolTable);
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400270#else
271 {
Ethan Nicholas041fd0a2020-10-07 16:42:04 -0400272 Rehydrator rehydrator(&fIRGenerator->fContext, fIRGenerator->fModifiers.get(),
273 fRootSymbolTable, this, SKSL_INCLUDE_sksl_gpu,
Brian Osmaneac49832020-09-18 11:49:22 -0400274 SKSL_INCLUDE_sksl_gpu_LENGTH);
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400275 fGpuSymbolTable = rehydrator.symbolTable();
Brian Osman00a8b5b2020-10-02 09:06:04 -0400276 gpuElements = rehydrator.elements();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -0400277 fModifiers.push_back(fIRGenerator->releaseModifiers());
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400278 }
279 {
Ethan Nicholas041fd0a2020-10-07 16:42:04 -0400280 Rehydrator rehydrator(&fIRGenerator->fContext, fIRGenerator->fModifiers.get(),
281 fGpuSymbolTable, this, SKSL_INCLUDE_sksl_vert,
Brian Osmaneac49832020-09-18 11:49:22 -0400282 SKSL_INCLUDE_sksl_vert_LENGTH);
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400283 fVertexSymbolTable = rehydrator.symbolTable();
Brian Osmanafa18ee2020-10-07 17:47:45 -0400284 vertElements = rehydrator.elements();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -0400285 fModifiers.push_back(fIRGenerator->releaseModifiers());
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400286 }
287 {
Ethan Nicholas041fd0a2020-10-07 16:42:04 -0400288 Rehydrator rehydrator(&fIRGenerator->fContext, fIRGenerator->fModifiers.get(),
289 fGpuSymbolTable, this, SKSL_INCLUDE_sksl_frag,
Brian Osmaneac49832020-09-18 11:49:22 -0400290 SKSL_INCLUDE_sksl_frag_LENGTH);
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400291 fFragmentSymbolTable = rehydrator.symbolTable();
Brian Osman00a8b5b2020-10-02 09:06:04 -0400292 fragElements = rehydrator.elements();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -0400293 fModifiers.push_back(fIRGenerator->releaseModifiers());
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400294 }
295#endif
John Stilesbc0c29e2020-09-28 13:13:40 -0400296 // Call counts are used to track dead-stripping and inlinability within the program being
297 // currently compiled, and always should start at zero for a new program. Zero out any call
298 // counts that were registered during the assembly of the intrinsics/include data. (If we
299 // actually use calls from inside the intrinsics, we will clone them into the program and they
300 // will get new call counts.)
Brian Osman00a8b5b2020-10-02 09:06:04 -0400301 reset_call_counts(&gpuElements);
Brian Osmanafa18ee2020-10-07 17:47:45 -0400302 reset_call_counts(&vertElements);
Brian Osman00a8b5b2020-10-02 09:06:04 -0400303 reset_call_counts(&fragElements);
John Stilesbc0c29e2020-09-28 13:13:40 -0400304
Brian Osman00a8b5b2020-10-02 09:06:04 -0400305 fGPUIntrinsics = std::make_unique<IRIntrinsicMap>(/*parent=*/nullptr);
306 grab_intrinsics(&gpuElements, fGPUIntrinsics.get());
307
Brian Osmanafa18ee2020-10-07 17:47:45 -0400308 fVertexIntrinsics = std::make_unique<IRIntrinsicMap>(fGPUIntrinsics.get());
309 grab_intrinsics(&vertElements, fVertexIntrinsics.get());
310
Brian Osman00a8b5b2020-10-02 09:06:04 -0400311 fFragmentIntrinsics = std::make_unique<IRIntrinsicMap>(fGPUIntrinsics.get());
312 grab_intrinsics(&fragElements, fFragmentIntrinsics.get());
ethannicholasb3058bd2016-07-01 08:22:01 -0700313}
314
John Stiles656427a2020-08-27 15:26:26 -0400315Compiler::~Compiler() {}
ethannicholasb3058bd2016-07-01 08:22:01 -0700316
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400317void Compiler::loadGeometryIntrinsics() {
318 if (fGeometrySymbolTable) {
319 return;
320 }
Brian Osmanafa18ee2020-10-07 17:47:45 -0400321 fGeometryIntrinsics = std::make_unique<IRIntrinsicMap>(fGPUIntrinsics.get());
322 std::vector<std::unique_ptr<ProgramElement>> geomElements;
Brian Osmandd496172020-08-08 08:17:18 -0400323 #if !SKSL_STANDALONE
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400324 {
Ethan Nicholas041fd0a2020-10-07 16:42:04 -0400325 Rehydrator rehydrator(&fIRGenerator->fContext, fIRGenerator->fModifiers.get(),
326 fGpuSymbolTable, this, SKSL_INCLUDE_sksl_geom,
327 SKSL_INCLUDE_sksl_geom_LENGTH);
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400328 fGeometrySymbolTable = rehydrator.symbolTable();
Brian Osmanafa18ee2020-10-07 17:47:45 -0400329 geomElements = rehydrator.elements();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -0400330 fModifiers.push_back(fIRGenerator->releaseModifiers());
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400331 }
332 #else
Ethan Nicholasb33fa3f2020-08-06 13:00:19 -0400333 this->processIncludeFile(Program::kGeometry_Kind, SKSL_GEOM_INCLUDE, fGpuSymbolTable,
Brian Osmanafa18ee2020-10-07 17:47:45 -0400334 &geomElements, &fGeometrySymbolTable);
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400335 #endif
Brian Osmanafa18ee2020-10-07 17:47:45 -0400336 grab_intrinsics(&geomElements, fGeometryIntrinsics.get());
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400337}
338
Brian Osman8e2ef022020-09-30 13:26:43 -0400339void Compiler::loadFPIntrinsics() {
340 if (fFPSymbolTable) {
341 return;
342 }
343 fFPIntrinsics = std::make_unique<IRIntrinsicMap>(fGPUIntrinsics.get());
344 std::vector<std::unique_ptr<ProgramElement>> fpElements;
345 #if !SKSL_STANDALONE
346 {
Ethan Nicholas041fd0a2020-10-07 16:42:04 -0400347 Rehydrator rehydrator(&fIRGenerator->fContext, fIRGenerator->fModifiers.get(),
348 fGpuSymbolTable, this, SKSL_INCLUDE_sksl_fp,
Brian Osman8e2ef022020-09-30 13:26:43 -0400349 SKSL_INCLUDE_sksl_fp_LENGTH);
350 fFPSymbolTable = rehydrator.symbolTable();
351 fpElements = rehydrator.elements();
352 }
353 #else
354 this->processIncludeFile(Program::kFragmentProcessor_Kind, SKSL_FP_INCLUDE, fGpuSymbolTable,
355 &fpElements, &fFPSymbolTable);
356 #endif
357 grab_intrinsics(&fpElements, fFPIntrinsics.get());
Brian Osman8e2ef022020-09-30 13:26:43 -0400358}
359
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400360void Compiler::loadPipelineIntrinsics() {
361 if (fPipelineSymbolTable) {
362 return;
363 }
Brian Osman00a8b5b2020-10-02 09:06:04 -0400364 fPipelineIntrinsics = std::make_unique<IRIntrinsicMap>(fGPUIntrinsics.get());
Brian Osman8e2ef022020-09-30 13:26:43 -0400365 std::vector<std::unique_ptr<ProgramElement>> pipelineIntrinics;
Brian Osmandd496172020-08-08 08:17:18 -0400366 #if !SKSL_STANDALONE
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400367 {
Ethan Nicholas041fd0a2020-10-07 16:42:04 -0400368 Rehydrator rehydrator(&fIRGenerator->fContext, fIRGenerator->fModifiers.get(),
369 fGpuSymbolTable, this, SKSL_INCLUDE_sksl_pipeline,
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400370 SKSL_INCLUDE_sksl_pipeline_LENGTH);
371 fPipelineSymbolTable = rehydrator.symbolTable();
Brian Osman8e2ef022020-09-30 13:26:43 -0400372 pipelineIntrinics = rehydrator.elements();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -0400373 fModifiers.push_back(fIRGenerator->releaseModifiers());
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400374 }
375 #else
376 this->processIncludeFile(Program::kPipelineStage_Kind, SKSL_PIPELINE_INCLUDE,
Brian Osman8e2ef022020-09-30 13:26:43 -0400377 fGpuSymbolTable, &pipelineIntrinics, &fPipelineSymbolTable);
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400378 #endif
Brian Osman8e2ef022020-09-30 13:26:43 -0400379 grab_intrinsics(&pipelineIntrinics, fPipelineIntrinsics.get());
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400380}
381
382void Compiler::loadInterpreterIntrinsics() {
383 if (fInterpreterSymbolTable) {
384 return;
385 }
Brian Osman00a8b5b2020-10-02 09:06:04 -0400386 fInterpreterIntrinsics = std::make_unique<IRIntrinsicMap>(/*parent=*/nullptr);
387 std::vector<std::unique_ptr<ProgramElement>> interpElements;
Brian Osmandd496172020-08-08 08:17:18 -0400388 #if !SKSL_STANDALONE
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400389 {
Ethan Nicholas041fd0a2020-10-07 16:42:04 -0400390 Rehydrator rehydrator(&fIRGenerator->fContext, fIRGenerator->fModifiers.get(),
391 fRootSymbolTable, this, SKSL_INCLUDE_sksl_interp,
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400392 SKSL_INCLUDE_sksl_interp_LENGTH);
393 fInterpreterSymbolTable = rehydrator.symbolTable();
Brian Osman00a8b5b2020-10-02 09:06:04 -0400394 interpElements = rehydrator.elements();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -0400395 fModifiers.push_back(fIRGenerator->releaseModifiers());
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400396 }
397 #else
398 this->processIncludeFile(Program::kGeneric_Kind, SKSL_INTERP_INCLUDE,
Brian Osman00a8b5b2020-10-02 09:06:04 -0400399 fIRGenerator->fSymbolTable, &interpElements,
Ethan Nicholasb33fa3f2020-08-06 13:00:19 -0400400 &fInterpreterSymbolTable);
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400401 #endif
Brian Osman00a8b5b2020-10-02 09:06:04 -0400402 grab_intrinsics(&interpElements, fInterpreterIntrinsics.get());
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400403}
404
Ethan Nicholasb33fa3f2020-08-06 13:00:19 -0400405void Compiler::processIncludeFile(Program::Kind kind, const char* path,
Ethan Nicholas8da1e652019-05-24 11:01:59 -0400406 std::shared_ptr<SymbolTable> base,
407 std::vector<std::unique_ptr<ProgramElement>>* outElements,
408 std::shared_ptr<SymbolTable>* outSymbolTable) {
Ethan Nicholasb33fa3f2020-08-06 13:00:19 -0400409 std::ifstream in(path);
Brian Osmane498b3c2020-09-23 14:42:11 -0400410 std::unique_ptr<String> text = std::make_unique<String>(std::istreambuf_iterator<char>(in),
411 std::istreambuf_iterator<char>());
Ethan Nicholasb33fa3f2020-08-06 13:00:19 -0400412 if (in.rdstate()) {
413 printf("error reading %s\n", path);
414 abort();
415 }
Brian Osmane498b3c2020-09-23 14:42:11 -0400416 const String* source = fRootSymbolTable->takeOwnershipOfString(std::move(text));
Ethan Nicholasb33fa3f2020-08-06 13:00:19 -0400417 fSource = source;
Ethan Nicholas8da1e652019-05-24 11:01:59 -0400418 Program::Settings settings;
Ethan Nicholasa11035b2019-11-26 16:27:47 -0500419#if !defined(SKSL_STANDALONE) & SK_SUPPORT_GPU
420 GrContextOptions opts;
421 GrShaderCaps caps(opts);
422 settings.fCaps = &caps;
423#endif
John Stiles881a10c2020-09-19 10:13:24 -0400424 SkASSERT(fIRGenerator->fCanInline);
425 fIRGenerator->fCanInline = false;
Brian Osmane498b3c2020-09-23 14:42:11 -0400426 fIRGenerator->start(&settings, base ? base : fRootSymbolTable, nullptr, true);
Ethan Nicholasb33fa3f2020-08-06 13:00:19 -0400427 fIRGenerator->convertProgram(kind, source->c_str(), source->length(), outElements);
John Stiles881a10c2020-09-19 10:13:24 -0400428 fIRGenerator->fCanInline = true;
Ethan Nicholas8da1e652019-05-24 11:01:59 -0400429 if (this->fErrorCount) {
430 printf("Unexpected errors: %s\n", this->fErrorText.c_str());
John Stiles88f3b682020-10-06 13:37:52 -0400431 SkDEBUGFAILF("%s %s\n", path, this->fErrorText.c_str());
Ethan Nicholas8da1e652019-05-24 11:01:59 -0400432 }
Ethan Nicholas8da1e652019-05-24 11:01:59 -0400433 *outSymbolTable = fIRGenerator->fSymbolTable;
Ethan Nicholasa11035b2019-11-26 16:27:47 -0500434#ifdef SK_DEBUG
435 fSource = nullptr;
436#endif
Ethan Nicholas041fd0a2020-10-07 16:42:04 -0400437 fModifiers.push_back(fIRGenerator->releaseModifiers());
Brian Osmane498b3c2020-09-23 14:42:11 -0400438 fIRGenerator->finish();
Ethan Nicholas8da1e652019-05-24 11:01:59 -0400439}
440
ethannicholas22f939e2016-10-13 13:25:34 -0700441// add the definition created by assigning to the lvalue to the definition set
Ethan Nicholas86a43402017-01-19 13:32:00 -0500442void Compiler::addDefinition(const Expression* lvalue, std::unique_ptr<Expression>* expr,
443 DefinitionMap* definitions) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400444 switch (lvalue->kind()) {
445 case Expression::Kind::kVariableReference: {
Brian Osman79457ef2020-09-24 15:01:27 -0400446 const Variable& var = *lvalue->as<VariableReference>().fVariable;
Ethan Nicholas041fd0a2020-10-07 16:42:04 -0400447 if (var.storage() == Variable::kLocal_Storage) {
ethannicholas22f939e2016-10-13 13:25:34 -0700448 (*definitions)[&var] = expr;
449 }
450 break;
451 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400452 case Expression::Kind::kSwizzle:
ethannicholas22f939e2016-10-13 13:25:34 -0700453 // We consider the variable written to as long as at least some of its components have
454 // been written to. This will lead to some false negatives (we won't catch it if you
455 // write to foo.x and then read foo.y), but being stricter could lead to false positives
Mike Klein6ad99092016-10-26 10:35:22 -0400456 // (we write to foo.x, and then pass foo to a function which happens to only read foo.x,
457 // 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 -0700458 // more complicated whole-program analysis. This is probably good enough.
John Stilesa5a97b42020-08-18 11:19:07 -0400459 this->addDefinition(lvalue->as<Swizzle>().fBase.get(),
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400460 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
ethannicholas22f939e2016-10-13 13:25:34 -0700461 definitions);
462 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400463 case Expression::Kind::kIndex:
ethannicholas22f939e2016-10-13 13:25:34 -0700464 // see comments in Swizzle
John Stilesa5a97b42020-08-18 11:19:07 -0400465 this->addDefinition(lvalue->as<IndexExpression>().fBase.get(),
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400466 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
ethannicholas22f939e2016-10-13 13:25:34 -0700467 definitions);
468 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400469 case Expression::Kind::kFieldAccess:
ethannicholas22f939e2016-10-13 13:25:34 -0700470 // see comments in Swizzle
John Stilesa5a97b42020-08-18 11:19:07 -0400471 this->addDefinition(lvalue->as<FieldAccess>().fBase.get(),
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400472 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
ethannicholas22f939e2016-10-13 13:25:34 -0700473 definitions);
474 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400475 case Expression::Kind::kTernary:
Ethan Nicholasa583b812018-01-18 13:32:11 -0500476 // To simplify analysis, we just pretend that we write to both sides of the ternary.
477 // This allows for false positives (meaning we fail to detect that a variable might not
478 // have been assigned), but is preferable to false negatives.
Ethan Nicholasdd218162020-10-08 05:48:01 -0400479 this->addDefinition(lvalue->as<TernaryExpression>().ifTrue().get(),
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400480 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
Ethan Nicholasa583b812018-01-18 13:32:11 -0500481 definitions);
Ethan Nicholasdd218162020-10-08 05:48:01 -0400482 this->addDefinition(lvalue->as<TernaryExpression>().ifFalse().get(),
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400483 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
Ethan Nicholasa583b812018-01-18 13:32:11 -0500484 definitions);
485 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400486 case Expression::Kind::kExternalValue:
Ethan Nicholas91164d12019-05-15 15:29:54 -0400487 break;
ethannicholas22f939e2016-10-13 13:25:34 -0700488 default:
489 // not an lvalue, can't happen
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400490 SkASSERT(false);
ethannicholas22f939e2016-10-13 13:25:34 -0700491 }
492}
493
494// add local variables defined by this node to the set
Mike Klein6ad99092016-10-26 10:35:22 -0400495void Compiler::addDefinitions(const BasicBlock::Node& node,
Ethan Nicholas86a43402017-01-19 13:32:00 -0500496 DefinitionMap* definitions) {
John Stiles70025e52020-09-28 16:08:58 -0400497 if (node.isExpression()) {
498 Expression* expr = node.expression()->get();
499 switch (expr->kind()) {
500 case Expression::Kind::kBinary: {
501 BinaryExpression* b = &expr->as<BinaryExpression>();
502 if (b->getOperator() == Token::Kind::TK_EQ) {
503 this->addDefinition(&b->left(), &b->rightPointer(), definitions);
504 } else if (Compiler::IsAssignment(b->getOperator())) {
505 this->addDefinition(
506 &b->left(),
507 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
508 definitions);
Ethan Nicholas86a43402017-01-19 13:32:00 -0500509
ethannicholas22f939e2016-10-13 13:25:34 -0700510 }
John Stiles70025e52020-09-28 16:08:58 -0400511 break;
ethannicholas22f939e2016-10-13 13:25:34 -0700512 }
John Stiles70025e52020-09-28 16:08:58 -0400513 case Expression::Kind::kFunctionCall: {
514 const FunctionCall& c = expr->as<FunctionCall>();
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400515 for (size_t i = 0; i < c.function().fParameters.size(); ++i) {
Ethan Nicholas041fd0a2020-10-07 16:42:04 -0400516 if (c.function().fParameters[i]->modifiers().fFlags & Modifiers::kOut_Flag) {
John Stiles70025e52020-09-28 16:08:58 -0400517 this->addDefinition(
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400518 c.arguments()[i].get(),
John Stiles70025e52020-09-28 16:08:58 -0400519 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
520 definitions);
521 }
522 }
523 break;
524 }
525 case Expression::Kind::kPrefix: {
526 const PrefixExpression* p = &expr->as<PrefixExpression>();
527 if (p->fOperator == Token::Kind::TK_MINUSMINUS ||
528 p->fOperator == Token::Kind::TK_PLUSPLUS) {
529 this->addDefinition(
530 p->fOperand.get(),
531 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
532 definitions);
533 }
534 break;
535 }
536 case Expression::Kind::kPostfix: {
537 const PostfixExpression* p = &expr->as<PostfixExpression>();
538 if (p->fOperator == Token::Kind::TK_MINUSMINUS ||
539 p->fOperator == Token::Kind::TK_PLUSPLUS) {
540 this->addDefinition(
541 p->fOperand.get(),
542 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
543 definitions);
544 }
545 break;
546 }
547 case Expression::Kind::kVariableReference: {
548 const VariableReference* v = &expr->as<VariableReference>();
549 if (v->fRefKind != VariableReference::kRead_RefKind) {
550 this->addDefinition(
551 v,
552 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
553 definitions);
554 }
555 break;
556 }
557 default:
558 break;
ethannicholas22f939e2016-10-13 13:25:34 -0700559 }
John Stiles70025e52020-09-28 16:08:58 -0400560 } else if (node.isStatement()) {
561 Statement* stmt = node.statement()->get();
562 if (stmt->is<VarDeclaration>()) {
563 VarDeclaration& vd = stmt->as<VarDeclaration>();
564 if (vd.fValue) {
565 (*definitions)[vd.fVar] = &vd.fValue;
ethannicholas22f939e2016-10-13 13:25:34 -0700566 }
ethannicholas22f939e2016-10-13 13:25:34 -0700567 }
568 }
569}
570
John Stilese6150002020-10-05 12:03:53 -0400571void Compiler::scanCFG(CFG* cfg, BlockId blockId, SkBitSet* processedSet) {
ethannicholas22f939e2016-10-13 13:25:34 -0700572 BasicBlock& block = cfg->fBlocks[blockId];
573
574 // compute definitions after this block
Ethan Nicholas86a43402017-01-19 13:32:00 -0500575 DefinitionMap after = block.fBefore;
ethannicholas22f939e2016-10-13 13:25:34 -0700576 for (const BasicBlock::Node& n : block.fNodes) {
577 this->addDefinitions(n, &after);
578 }
579
580 // propagate definitions to exits
581 for (BlockId exitId : block.fExits) {
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400582 if (exitId == blockId) {
583 continue;
584 }
ethannicholas22f939e2016-10-13 13:25:34 -0700585 BasicBlock& exit = cfg->fBlocks[exitId];
586 for (const auto& pair : after) {
Ethan Nicholas86a43402017-01-19 13:32:00 -0500587 std::unique_ptr<Expression>* e1 = pair.second;
588 auto found = exit.fBefore.find(pair.first);
589 if (found == exit.fBefore.end()) {
John Stilese6150002020-10-05 12:03:53 -0400590 // exit has no definition for it, just copy it and reprocess exit block
591 processedSet->reset(exitId);
ethannicholas22f939e2016-10-13 13:25:34 -0700592 exit.fBefore[pair.first] = e1;
593 } else {
Ethan Nicholas86a43402017-01-19 13:32:00 -0500594 // exit has a (possibly different) value already defined
595 std::unique_ptr<Expression>* e2 = exit.fBefore[pair.first];
ethannicholas22f939e2016-10-13 13:25:34 -0700596 if (e1 != e2) {
John Stilese6150002020-10-05 12:03:53 -0400597 // definition has changed, merge and reprocess the exit block
598 processedSet->reset(exitId);
Ethan Nicholasaf197692017-02-27 13:26:45 -0500599 if (e1 && e2) {
600 exit.fBefore[pair.first] =
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400601 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression;
Ethan Nicholasaf197692017-02-27 13:26:45 -0500602 } else {
603 exit.fBefore[pair.first] = nullptr;
604 }
ethannicholas22f939e2016-10-13 13:25:34 -0700605 }
606 }
607 }
608 }
609}
610
611// returns a map which maps all local variables in the function to null, indicating that their value
612// is initially unknown
Ethan Nicholas86a43402017-01-19 13:32:00 -0500613static DefinitionMap compute_start_state(const CFG& cfg) {
614 DefinitionMap result;
Mike Klein6ad99092016-10-26 10:35:22 -0400615 for (const auto& block : cfg.fBlocks) {
616 for (const auto& node : block.fNodes) {
John Stiles70025e52020-09-28 16:08:58 -0400617 if (node.isStatement()) {
Ethan Nicholascb670962017-04-20 19:31:52 -0400618 const Statement* s = node.statement()->get();
Brian Osmanc0213602020-10-06 14:43:32 -0400619 if (s->is<VarDeclaration>()) {
620 result[s->as<VarDeclaration>().fVar] = nullptr;
ethannicholas22f939e2016-10-13 13:25:34 -0700621 }
622 }
623 }
624 }
625 return result;
626}
627
Ethan Nicholascb670962017-04-20 19:31:52 -0400628/**
629 * Returns true if assigning to this lvalue has no effect.
630 */
631static bool is_dead(const Expression& lvalue) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400632 switch (lvalue.kind()) {
633 case Expression::Kind::kVariableReference:
Brian Osman79457ef2020-09-24 15:01:27 -0400634 return lvalue.as<VariableReference>().fVariable->dead();
Ethan Nicholase6592142020-09-08 10:22:09 -0400635 case Expression::Kind::kSwizzle:
John Stilesa5a97b42020-08-18 11:19:07 -0400636 return is_dead(*lvalue.as<Swizzle>().fBase);
Ethan Nicholase6592142020-09-08 10:22:09 -0400637 case Expression::Kind::kFieldAccess:
John Stilesa5a97b42020-08-18 11:19:07 -0400638 return is_dead(*lvalue.as<FieldAccess>().fBase);
Ethan Nicholase6592142020-09-08 10:22:09 -0400639 case Expression::Kind::kIndex: {
John Stilesa5a97b42020-08-18 11:19:07 -0400640 const IndexExpression& idx = lvalue.as<IndexExpression>();
Ethan Nicholas2a099da2020-01-02 14:40:54 -0500641 return is_dead(*idx.fBase) &&
642 !idx.fIndex->hasProperty(Expression::Property::kSideEffects);
Ethan Nicholascb670962017-04-20 19:31:52 -0400643 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400644 case Expression::Kind::kTernary: {
John Stilesa5a97b42020-08-18 11:19:07 -0400645 const TernaryExpression& t = lvalue.as<TernaryExpression>();
Ethan Nicholasdd218162020-10-08 05:48:01 -0400646 return !t.test()->hasSideEffects() && is_dead(*t.ifTrue()) && is_dead(*t.ifFalse());
Ethan Nicholasa583b812018-01-18 13:32:11 -0500647 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400648 case Expression::Kind::kExternalValue:
Ethan Nicholas91164d12019-05-15 15:29:54 -0400649 return false;
Ethan Nicholascb670962017-04-20 19:31:52 -0400650 default:
Ethan Nicholas2a099da2020-01-02 14:40:54 -0500651#ifdef SK_DEBUG
Ethan Nicholascb670962017-04-20 19:31:52 -0400652 ABORT("invalid lvalue: %s\n", lvalue.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -0500653#endif
654 return false;
Ethan Nicholascb670962017-04-20 19:31:52 -0400655 }
656}
ethannicholas22f939e2016-10-13 13:25:34 -0700657
Ethan Nicholascb670962017-04-20 19:31:52 -0400658/**
659 * Returns true if this is an assignment which can be collapsed down to just the right hand side due
660 * to a dead target and lack of side effects on the left hand side.
661 */
662static bool dead_assignment(const BinaryExpression& b) {
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400663 if (!Compiler::IsAssignment(b.getOperator())) {
Ethan Nicholascb670962017-04-20 19:31:52 -0400664 return false;
665 }
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400666 return is_dead(b.left());
Ethan Nicholascb670962017-04-20 19:31:52 -0400667}
668
669void Compiler::computeDataFlow(CFG* cfg) {
670 cfg->fBlocks[cfg->fStart].fBefore = compute_start_state(*cfg);
John Stilese6150002020-10-05 12:03:53 -0400671
672 // We set bits in the "processed" set after a block has been scanned.
673 SkBitSet processedSet(cfg->fBlocks.size());
674 while (SkBitSet::OptionalIndex blockId = processedSet.findFirstUnset()) {
675 processedSet.set(*blockId);
676 this->scanCFG(cfg, *blockId, &processedSet);
ethannicholas22f939e2016-10-13 13:25:34 -0700677 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400678}
679
680/**
681 * Attempts to replace the expression pointed to by iter with a new one (in both the CFG and the
682 * IR). If the expression can be cleanly removed, returns true and updates the iterator to point to
683 * the newly-inserted element. Otherwise updates only the IR and returns false (and the CFG will
684 * need to be regenerated).
685 */
John Stilesafbf8992020-08-18 10:08:21 -0400686static bool try_replace_expression(BasicBlock* b,
687 std::vector<BasicBlock::Node>::iterator* iter,
688 std::unique_ptr<Expression>* newExpression) {
Ethan Nicholascb670962017-04-20 19:31:52 -0400689 std::unique_ptr<Expression>* target = (*iter)->expression();
690 if (!b->tryRemoveExpression(iter)) {
691 *target = std::move(*newExpression);
692 return false;
693 }
694 *target = std::move(*newExpression);
695 return b->tryInsertExpression(iter, target);
696}
697
698/**
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400699 * Returns true if the expression is a constant numeric literal with the specified value, or a
700 * constant vector with all elements equal to the specified value.
Ethan Nicholascb670962017-04-20 19:31:52 -0400701 */
Ethan Nicholasa3f22f12020-10-01 12:13:17 -0400702template <typename T = SKSL_FLOAT>
John Stiles9d944232020-08-19 09:56:49 -0400703static bool is_constant(const Expression& expr, T value) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400704 switch (expr.kind()) {
705 case Expression::Kind::kIntLiteral:
Ethan Nicholase96cdd12020-09-28 16:27:18 -0400706 return expr.as<IntLiteral>().value() == value;
John Stiles9d944232020-08-19 09:56:49 -0400707
Ethan Nicholase6592142020-09-08 10:22:09 -0400708 case Expression::Kind::kFloatLiteral:
Ethan Nicholasa3f22f12020-10-01 12:13:17 -0400709 return expr.as<FloatLiteral>().value() == value;
John Stiles9d944232020-08-19 09:56:49 -0400710
Ethan Nicholase6592142020-09-08 10:22:09 -0400711 case Expression::Kind::kConstructor: {
John Stiles9d944232020-08-19 09:56:49 -0400712 const Constructor& constructor = expr.as<Constructor>();
713 if (constructor.isCompileTimeConstant()) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400714 const Type& constructorType = constructor.type();
715 bool isFloat = constructorType.columns() > 1
716 ? constructorType.componentType().isFloat()
717 : constructorType.isFloat();
718 switch (constructorType.typeKind()) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400719 case Type::TypeKind::kVector:
Ethan Nicholas30d30222020-09-11 12:27:26 -0400720 for (int i = 0; i < constructorType.columns(); ++i) {
John Stiles9d944232020-08-19 09:56:49 -0400721 if (isFloat) {
722 if (constructor.getFVecComponent(i) != value) {
723 return false;
724 }
725 } else {
726 if (constructor.getIVecComponent(i) != value) {
727 return false;
728 }
729 }
Ethan Nicholasd188c182019-06-10 15:55:38 -0400730 }
John Stiles9d944232020-08-19 09:56:49 -0400731 return true;
732
Ethan Nicholase6592142020-09-08 10:22:09 -0400733 case Type::TypeKind::kScalar:
Ethan Nicholasf70f0442020-09-29 12:41:35 -0400734 SkASSERT(constructor.arguments().size() == 1);
735 return is_constant<T>(*constructor.arguments()[0], value);
John Stiles9d944232020-08-19 09:56:49 -0400736
737 default:
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400738 return false;
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400739 }
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400740 }
741 return false;
742 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400743 default:
744 return false;
745 }
746}
747
748/**
749 * Collapses the binary expression pointed to by iter down to just the right side (in both the IR
750 * and CFG structures).
751 */
John Stilesafbf8992020-08-18 10:08:21 -0400752static void delete_left(BasicBlock* b,
753 std::vector<BasicBlock::Node>::iterator* iter,
754 bool* outUpdated,
755 bool* outNeedsRescan) {
Ethan Nicholascb670962017-04-20 19:31:52 -0400756 *outUpdated = true;
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400757 std::unique_ptr<Expression>* target = (*iter)->expression();
John Stilesa5a97b42020-08-18 11:19:07 -0400758 BinaryExpression& bin = (*target)->as<BinaryExpression>();
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400759 Expression& left = bin.left();
760 std::unique_ptr<Expression>& rightPointer = bin.rightPointer();
761 SkASSERT(!left.hasSideEffects());
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400762 bool result;
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400763 if (bin.getOperator() == Token::Kind::TK_EQ) {
764 result = b->tryRemoveLValueBefore(iter, &left);
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400765 } else {
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400766 result = b->tryRemoveExpressionBefore(iter, &left);
Ethan Nicholascb670962017-04-20 19:31:52 -0400767 }
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400768 *target = std::move(rightPointer);
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400769 if (!result) {
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400770 *outNeedsRescan = true;
771 return;
772 }
773 if (*iter == b->fNodes.begin()) {
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400774 *outNeedsRescan = true;
775 return;
776 }
777 --(*iter);
John Stiles70025e52020-09-28 16:08:58 -0400778 if (!(*iter)->isExpression() || (*iter)->expression() != &rightPointer) {
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400779 *outNeedsRescan = true;
780 return;
781 }
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400782 *iter = b->fNodes.erase(*iter);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400783 SkASSERT((*iter)->expression() == target);
Ethan Nicholascb670962017-04-20 19:31:52 -0400784}
785
786/**
787 * Collapses the binary expression pointed to by iter down to just the left side (in both the IR and
788 * CFG structures).
789 */
John Stilesafbf8992020-08-18 10:08:21 -0400790static void delete_right(BasicBlock* b,
791 std::vector<BasicBlock::Node>::iterator* iter,
792 bool* outUpdated,
793 bool* outNeedsRescan) {
Ethan Nicholascb670962017-04-20 19:31:52 -0400794 *outUpdated = true;
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400795 std::unique_ptr<Expression>* target = (*iter)->expression();
John Stilesa5a97b42020-08-18 11:19:07 -0400796 BinaryExpression& bin = (*target)->as<BinaryExpression>();
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400797 std::unique_ptr<Expression>& leftPointer = bin.leftPointer();
798 Expression& right = bin.right();
799 SkASSERT(!right.hasSideEffects());
800 if (!b->tryRemoveExpressionBefore(iter, &right)) {
801 *target = std::move(leftPointer);
Ethan Nicholascb670962017-04-20 19:31:52 -0400802 *outNeedsRescan = true;
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400803 return;
Ethan Nicholascb670962017-04-20 19:31:52 -0400804 }
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400805 *target = std::move(leftPointer);
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400806 if (*iter == b->fNodes.begin()) {
807 *outNeedsRescan = true;
808 return;
809 }
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400810 --(*iter);
John Stiles70025e52020-09-28 16:08:58 -0400811 if ((!(*iter)->isExpression() || (*iter)->expression() != &leftPointer)) {
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400812 *outNeedsRescan = true;
813 return;
814 }
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400815 *iter = b->fNodes.erase(*iter);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400816 SkASSERT((*iter)->expression() == target);
Ethan Nicholascb670962017-04-20 19:31:52 -0400817}
818
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400819/**
820 * Constructs the specified type using a single argument.
821 */
Ethan Nicholas30d30222020-09-11 12:27:26 -0400822static std::unique_ptr<Expression> construct(const Type* type, std::unique_ptr<Expression> v) {
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400823 std::vector<std::unique_ptr<Expression>> args;
824 args.push_back(std::move(v));
Ethan Nicholase6592142020-09-08 10:22:09 -0400825 std::unique_ptr<Expression> result = std::make_unique<Constructor>(-1, type, std::move(args));
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400826 return result;
827}
828
829/**
830 * Used in the implementations of vectorize_left and vectorize_right. Given a vector type and an
831 * expression x, deletes the expression pointed to by iter and replaces it with <type>(x).
832 */
833static void vectorize(BasicBlock* b,
834 std::vector<BasicBlock::Node>::iterator* iter,
835 const Type& type,
836 std::unique_ptr<Expression>* otherExpression,
837 bool* outUpdated,
838 bool* outNeedsRescan) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400839 SkASSERT((*(*iter)->expression())->kind() == Expression::Kind::kBinary);
840 SkASSERT(type.typeKind() == Type::TypeKind::kVector);
Ethan Nicholas30d30222020-09-11 12:27:26 -0400841 SkASSERT((*otherExpression)->type().typeKind() == Type::TypeKind::kScalar);
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400842 *outUpdated = true;
843 std::unique_ptr<Expression>* target = (*iter)->expression();
844 if (!b->tryRemoveExpression(iter)) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400845 *target = construct(&type, std::move(*otherExpression));
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400846 *outNeedsRescan = true;
847 } else {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400848 *target = construct(&type, std::move(*otherExpression));
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400849 if (!b->tryInsertExpression(iter, target)) {
850 *outNeedsRescan = true;
851 }
852 }
853}
854
855/**
856 * Given a binary expression of the form x <op> vec<n>(y), deletes the right side and vectorizes the
857 * left to yield vec<n>(x).
858 */
859static void vectorize_left(BasicBlock* b,
860 std::vector<BasicBlock::Node>::iterator* iter,
861 bool* outUpdated,
862 bool* outNeedsRescan) {
John Stilesa5a97b42020-08-18 11:19:07 -0400863 BinaryExpression& bin = (*(*iter)->expression())->as<BinaryExpression>();
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400864 vectorize(b, iter, bin.right().type(), &bin.leftPointer(), outUpdated, outNeedsRescan);
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400865}
866
867/**
868 * Given a binary expression of the form vec<n>(x) <op> y, deletes the left side and vectorizes the
869 * right to yield vec<n>(y).
870 */
871static void vectorize_right(BasicBlock* b,
872 std::vector<BasicBlock::Node>::iterator* iter,
873 bool* outUpdated,
874 bool* outNeedsRescan) {
John Stilesa5a97b42020-08-18 11:19:07 -0400875 BinaryExpression& bin = (*(*iter)->expression())->as<BinaryExpression>();
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400876 vectorize(b, iter, bin.left().type(), &bin.rightPointer(), outUpdated, outNeedsRescan);
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400877}
878
879// Mark that an expression which we were writing to is no longer being written to
John Stilesa5a97b42020-08-18 11:19:07 -0400880static void clear_write(Expression& expr) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400881 switch (expr.kind()) {
882 case Expression::Kind::kVariableReference: {
John Stilesa5a97b42020-08-18 11:19:07 -0400883 expr.as<VariableReference>().setRefKind(VariableReference::kRead_RefKind);
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400884 break;
885 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400886 case Expression::Kind::kFieldAccess:
John Stilesa5a97b42020-08-18 11:19:07 -0400887 clear_write(*expr.as<FieldAccess>().fBase);
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400888 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400889 case Expression::Kind::kSwizzle:
John Stilesa5a97b42020-08-18 11:19:07 -0400890 clear_write(*expr.as<Swizzle>().fBase);
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400891 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400892 case Expression::Kind::kIndex:
John Stilesa5a97b42020-08-18 11:19:07 -0400893 clear_write(*expr.as<IndexExpression>().fBase);
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400894 break;
895 default:
896 ABORT("shouldn't be writing to this kind of expression\n");
897 break;
898 }
899}
900
Ethan Nicholascb670962017-04-20 19:31:52 -0400901void Compiler::simplifyExpression(DefinitionMap& definitions,
902 BasicBlock& b,
903 std::vector<BasicBlock::Node>::iterator* iter,
904 std::unordered_set<const Variable*>* undefinedVariables,
905 bool* outUpdated,
906 bool* outNeedsRescan) {
907 Expression* expr = (*iter)->expression()->get();
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400908 SkASSERT(expr);
Ethan Nicholascb670962017-04-20 19:31:52 -0400909 if ((*iter)->fConstantPropagation) {
910 std::unique_ptr<Expression> optimized = expr->constantPropagate(*fIRGenerator, definitions);
911 if (optimized) {
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400912 *outUpdated = true;
Ethan Nicholas30d30222020-09-11 12:27:26 -0400913 optimized = fIRGenerator->coerce(std::move(optimized), expr->type());
Ethan Nicholas1d881522020-09-11 09:32:54 -0400914 SkASSERT(optimized);
Ethan Nicholascb670962017-04-20 19:31:52 -0400915 if (!try_replace_expression(&b, iter, &optimized)) {
916 *outNeedsRescan = true;
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400917 return;
Ethan Nicholascb670962017-04-20 19:31:52 -0400918 }
John Stiles70025e52020-09-28 16:08:58 -0400919 SkASSERT((*iter)->isExpression());
Ethan Nicholascb670962017-04-20 19:31:52 -0400920 expr = (*iter)->expression()->get();
Ethan Nicholascb670962017-04-20 19:31:52 -0400921 }
922 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400923 switch (expr->kind()) {
924 case Expression::Kind::kVariableReference: {
John Stilesa5a97b42020-08-18 11:19:07 -0400925 const VariableReference& ref = expr->as<VariableReference>();
Brian Osman79457ef2020-09-24 15:01:27 -0400926 const Variable* var = ref.fVariable;
Ethan Nicholas8f7e28f2018-03-26 14:24:27 -0400927 if (ref.refKind() != VariableReference::kWrite_RefKind &&
928 ref.refKind() != VariableReference::kPointer_RefKind &&
Ethan Nicholas041fd0a2020-10-07 16:42:04 -0400929 var->storage() == Variable::kLocal_Storage && !definitions[var] &&
Brian Osman79457ef2020-09-24 15:01:27 -0400930 (*undefinedVariables).find(var) == (*undefinedVariables).end()) {
931 (*undefinedVariables).insert(var);
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000932 this->error(expr->fOffset,
Ethan Nicholase2c49992020-10-05 11:49:11 -0400933 "'" + var->name() + "' has not been assigned");
Ethan Nicholascb670962017-04-20 19:31:52 -0400934 }
935 break;
936 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400937 case Expression::Kind::kTernary: {
John Stiles403a3632020-08-20 12:11:48 -0400938 TernaryExpression* t = &expr->as<TernaryExpression>();
Ethan Nicholasdd218162020-10-08 05:48:01 -0400939 if (t->test()->is<BoolLiteral>()) {
Ethan Nicholascb670962017-04-20 19:31:52 -0400940 // ternary has a constant test, replace it with either the true or
941 // false branch
Ethan Nicholasdd218162020-10-08 05:48:01 -0400942 if (t->test()->as<BoolLiteral>().value()) {
943 (*iter)->setExpression(std::move(t->ifTrue()));
Ethan Nicholascb670962017-04-20 19:31:52 -0400944 } else {
Ethan Nicholasdd218162020-10-08 05:48:01 -0400945 (*iter)->setExpression(std::move(t->ifFalse()));
Ethan Nicholascb670962017-04-20 19:31:52 -0400946 }
947 *outUpdated = true;
948 *outNeedsRescan = true;
949 }
950 break;
951 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400952 case Expression::Kind::kBinary: {
John Stiles403a3632020-08-20 12:11:48 -0400953 BinaryExpression* bin = &expr->as<BinaryExpression>();
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400954 if (dead_assignment(*bin)) {
955 delete_left(&b, iter, outUpdated, outNeedsRescan);
956 break;
957 }
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400958 Expression& left = bin->left();
959 Expression& right = bin->right();
960 const Type& leftType = left.type();
961 const Type& rightType = right.type();
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400962 // collapse useless expressions like x * 1 or x + 0
Ethan Nicholas30d30222020-09-11 12:27:26 -0400963 if (((leftType.typeKind() != Type::TypeKind::kScalar) &&
964 (leftType.typeKind() != Type::TypeKind::kVector)) ||
965 ((rightType.typeKind() != Type::TypeKind::kScalar) &&
966 (rightType.typeKind() != Type::TypeKind::kVector))) {
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400967 break;
968 }
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400969 switch (bin->getOperator()) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400970 case Token::Kind::TK_STAR:
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400971 if (is_constant(left, 1)) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400972 if (leftType.typeKind() == Type::TypeKind::kVector &&
973 rightType.typeKind() == Type::TypeKind::kScalar) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400974 // float4(1) * x -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400975 vectorize_right(&b, iter, outUpdated, outNeedsRescan);
976 } else {
977 // 1 * x -> x
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400978 // 1 * float4(x) -> float4(x)
979 // float4(1) * float4(x) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400980 delete_left(&b, iter, outUpdated, outNeedsRescan);
981 }
982 }
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400983 else if (is_constant(left, 0)) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400984 if (leftType.typeKind() == Type::TypeKind::kScalar &&
985 rightType.typeKind() == Type::TypeKind::kVector &&
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400986 !right.hasSideEffects()) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400987 // 0 * float4(x) -> float4(0)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400988 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
989 } else {
990 // 0 * x -> 0
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400991 // float4(0) * x -> float4(0)
992 // float4(0) * float4(x) -> float4(0)
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400993 if (!right.hasSideEffects()) {
Ethan Nicholas51493ee2017-12-11 12:34:33 -0500994 delete_right(&b, iter, outUpdated, outNeedsRescan);
995 }
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400996 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400997 }
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400998 else if (is_constant(right, 1)) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400999 if (leftType.typeKind() == Type::TypeKind::kScalar &&
1000 rightType.typeKind() == Type::TypeKind::kVector) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -04001001 // x * float4(1) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -04001002 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
1003 } else {
1004 // x * 1 -> x
Ethan Nicholas5af9ea32017-07-28 15:19:46 -04001005 // float4(x) * 1 -> float4(x)
1006 // float4(x) * float4(1) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -04001007 delete_right(&b, iter, outUpdated, outNeedsRescan);
1008 }
1009 }
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001010 else if (is_constant(right, 0)) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04001011 if (leftType.typeKind() == Type::TypeKind::kVector &&
1012 rightType.typeKind() == Type::TypeKind::kScalar &&
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001013 !left.hasSideEffects()) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -04001014 // float4(x) * 0 -> float4(0)
Ethan Nicholasfe53e582017-04-27 16:24:51 -04001015 vectorize_right(&b, iter, outUpdated, outNeedsRescan);
1016 } else {
1017 // x * 0 -> 0
Ethan Nicholas5af9ea32017-07-28 15:19:46 -04001018 // x * float4(0) -> float4(0)
1019 // float4(x) * float4(0) -> float4(0)
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001020 if (!left.hasSideEffects()) {
Ethan Nicholas51493ee2017-12-11 12:34:33 -05001021 delete_left(&b, iter, outUpdated, outNeedsRescan);
1022 }
Ethan Nicholasfe53e582017-04-27 16:24:51 -04001023 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001024 }
1025 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001026 case Token::Kind::TK_PLUS:
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001027 if (is_constant(left, 0)) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04001028 if (leftType.typeKind() == Type::TypeKind::kVector &&
1029 rightType.typeKind() == Type::TypeKind::kScalar) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -04001030 // float4(0) + x -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -04001031 vectorize_right(&b, iter, outUpdated, outNeedsRescan);
1032 } else {
1033 // 0 + x -> x
Ethan Nicholas5af9ea32017-07-28 15:19:46 -04001034 // 0 + float4(x) -> float4(x)
1035 // float4(0) + float4(x) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -04001036 delete_left(&b, iter, outUpdated, outNeedsRescan);
1037 }
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001038 } else if (is_constant(right, 0)) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04001039 if (leftType.typeKind() == Type::TypeKind::kScalar &&
1040 rightType.typeKind() == Type::TypeKind::kVector) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -04001041 // x + float4(0) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -04001042 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
1043 } else {
1044 // x + 0 -> x
Ethan Nicholas5af9ea32017-07-28 15:19:46 -04001045 // float4(x) + 0 -> float4(x)
1046 // float4(x) + float4(0) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -04001047 delete_right(&b, iter, outUpdated, outNeedsRescan);
1048 }
Ethan Nicholas56e42712017-04-21 10:23:37 -04001049 }
1050 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001051 case Token::Kind::TK_MINUS:
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001052 if (is_constant(right, 0)) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04001053 if (leftType.typeKind() == Type::TypeKind::kScalar &&
1054 rightType.typeKind() == Type::TypeKind::kVector) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -04001055 // x - float4(0) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -04001056 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
1057 } else {
1058 // x - 0 -> x
Ethan Nicholas5af9ea32017-07-28 15:19:46 -04001059 // float4(x) - 0 -> float4(x)
1060 // float4(x) - float4(0) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -04001061 delete_right(&b, iter, outUpdated, outNeedsRescan);
1062 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001063 }
1064 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001065 case Token::Kind::TK_SLASH:
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001066 if (is_constant(right, 1)) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04001067 if (leftType.typeKind() == Type::TypeKind::kScalar &&
1068 rightType.typeKind() == Type::TypeKind::kVector) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -04001069 // x / float4(1) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -04001070 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
1071 } else {
1072 // x / 1 -> x
Ethan Nicholas5af9ea32017-07-28 15:19:46 -04001073 // float4(x) / 1 -> float4(x)
1074 // float4(x) / float4(1) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -04001075 delete_right(&b, iter, outUpdated, outNeedsRescan);
1076 }
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001077 } else if (is_constant(left, 0)) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04001078 if (leftType.typeKind() == Type::TypeKind::kScalar &&
1079 rightType.typeKind() == Type::TypeKind::kVector &&
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001080 !right.hasSideEffects()) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -04001081 // 0 / float4(x) -> float4(0)
Ethan Nicholasfe53e582017-04-27 16:24:51 -04001082 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
1083 } else {
1084 // 0 / x -> 0
Ethan Nicholas5af9ea32017-07-28 15:19:46 -04001085 // float4(0) / x -> float4(0)
1086 // float4(0) / float4(x) -> float4(0)
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001087 if (!right.hasSideEffects()) {
Ethan Nicholas51493ee2017-12-11 12:34:33 -05001088 delete_right(&b, iter, outUpdated, outNeedsRescan);
1089 }
Ethan Nicholasfe53e582017-04-27 16:24:51 -04001090 }
1091 }
1092 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001093 case Token::Kind::TK_PLUSEQ:
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001094 if (is_constant(right, 0)) {
1095 clear_write(left);
Ethan Nicholasfe53e582017-04-27 16:24:51 -04001096 delete_right(&b, iter, outUpdated, outNeedsRescan);
1097 }
1098 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001099 case Token::Kind::TK_MINUSEQ:
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001100 if (is_constant(right, 0)) {
1101 clear_write(left);
Ethan Nicholasfe53e582017-04-27 16:24:51 -04001102 delete_right(&b, iter, outUpdated, outNeedsRescan);
1103 }
1104 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001105 case Token::Kind::TK_STAREQ:
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001106 if (is_constant(right, 1)) {
1107 clear_write(left);
Ethan Nicholasfe53e582017-04-27 16:24:51 -04001108 delete_right(&b, iter, outUpdated, outNeedsRescan);
1109 }
1110 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001111 case Token::Kind::TK_SLASHEQ:
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001112 if (is_constant(right, 1)) {
1113 clear_write(left);
Ethan Nicholascb670962017-04-20 19:31:52 -04001114 delete_right(&b, iter, outUpdated, outNeedsRescan);
1115 }
1116 break;
1117 default:
1118 break;
1119 }
Ethan Nicholas409f6f02019-09-17 12:34:39 -04001120 break;
1121 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001122 case Expression::Kind::kSwizzle: {
John Stiles403a3632020-08-20 12:11:48 -04001123 Swizzle& s = expr->as<Swizzle>();
Ethan Nicholas409f6f02019-09-17 12:34:39 -04001124 // detect identity swizzles like foo.rgba
Ethan Nicholas30d30222020-09-11 12:27:26 -04001125 if ((int) s.fComponents.size() == s.fBase->type().columns()) {
Ethan Nicholas409f6f02019-09-17 12:34:39 -04001126 bool identity = true;
1127 for (int i = 0; i < (int) s.fComponents.size(); ++i) {
1128 if (s.fComponents[i] != i) {
1129 identity = false;
1130 break;
1131 }
1132 }
1133 if (identity) {
1134 *outUpdated = true;
1135 if (!try_replace_expression(&b, iter, &s.fBase)) {
1136 *outNeedsRescan = true;
1137 return;
1138 }
John Stiles70025e52020-09-28 16:08:58 -04001139 SkASSERT((*iter)->isExpression());
Ethan Nicholas409f6f02019-09-17 12:34:39 -04001140 break;
1141 }
1142 }
1143 // detect swizzles of swizzles, e.g. replace foo.argb.r000 with foo.a000
Ethan Nicholase6592142020-09-08 10:22:09 -04001144 if (s.fBase->kind() == Expression::Kind::kSwizzle) {
John Stilesa5a97b42020-08-18 11:19:07 -04001145 Swizzle& base = s.fBase->as<Swizzle>();
Ethan Nicholas409f6f02019-09-17 12:34:39 -04001146 std::vector<int> final;
1147 for (int c : s.fComponents) {
Brian Osman25647672020-09-15 15:16:56 -04001148 final.push_back(base.fComponents[c]);
Ethan Nicholas409f6f02019-09-17 12:34:39 -04001149 }
1150 *outUpdated = true;
1151 std::unique_ptr<Expression> replacement(new Swizzle(*fContext, base.fBase->clone(),
1152 std::move(final)));
1153 if (!try_replace_expression(&b, iter, &replacement)) {
1154 *outNeedsRescan = true;
1155 return;
1156 }
John Stiles70025e52020-09-28 16:08:58 -04001157 SkASSERT((*iter)->isExpression());
Ethan Nicholas409f6f02019-09-17 12:34:39 -04001158 }
John Stiles30212b72020-06-11 17:55:07 -04001159 break;
Ethan Nicholascb670962017-04-20 19:31:52 -04001160 }
1161 default:
1162 break;
1163 }
1164}
1165
John Stiles92219b42020-06-15 12:32:24 -04001166// Returns true if this statement could potentially execute a break at the current level. We ignore
1167// nested loops and switches, since any breaks inside of them will merely break the loop / switch.
John Stilesb92641c2020-08-31 18:09:01 -04001168static bool contains_conditional_break(Statement& stmt) {
1169 class ContainsConditionalBreak : public ProgramVisitor {
1170 public:
1171 bool visitStatement(const Statement& stmt) override {
Ethan Nicholase6592142020-09-08 10:22:09 -04001172 switch (stmt.kind()) {
1173 case Statement::Kind::kBlock:
John Stilesb92641c2020-08-31 18:09:01 -04001174 return this->INHERITED::visitStatement(stmt);
1175
Ethan Nicholase6592142020-09-08 10:22:09 -04001176 case Statement::Kind::kBreak:
John Stilesb92641c2020-08-31 18:09:01 -04001177 return fInConditional > 0;
1178
Ethan Nicholase6592142020-09-08 10:22:09 -04001179 case Statement::Kind::kIf: {
John Stilesb92641c2020-08-31 18:09:01 -04001180 ++fInConditional;
1181 bool result = this->INHERITED::visitStatement(stmt);
1182 --fInConditional;
1183 return result;
1184 }
1185
1186 default:
1187 return false;
1188 }
1189 }
1190
1191 int fInConditional = 0;
1192 using INHERITED = ProgramVisitor;
1193 };
1194
1195 return ContainsConditionalBreak{}.visitStatement(stmt);
John Stiles92219b42020-06-15 12:32:24 -04001196}
1197
Ethan Nicholas5005a222018-08-24 13:06:27 -04001198// returns true if this statement definitely executes a break at the current level (we ignore
1199// nested loops and switches, since any breaks inside of them will merely break the loop / switch)
John Stilesb92641c2020-08-31 18:09:01 -04001200static bool contains_unconditional_break(Statement& stmt) {
1201 class ContainsUnconditionalBreak : public ProgramVisitor {
1202 public:
1203 bool visitStatement(const Statement& stmt) override {
Ethan Nicholase6592142020-09-08 10:22:09 -04001204 switch (stmt.kind()) {
1205 case Statement::Kind::kBlock:
John Stilesb92641c2020-08-31 18:09:01 -04001206 return this->INHERITED::visitStatement(stmt);
1207
Ethan Nicholase6592142020-09-08 10:22:09 -04001208 case Statement::Kind::kBreak:
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001209 return true;
John Stilesb92641c2020-08-31 18:09:01 -04001210
1211 default:
1212 return false;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001213 }
John Stilesb92641c2020-08-31 18:09:01 -04001214 }
John Stiles92219b42020-06-15 12:32:24 -04001215
John Stilesb92641c2020-08-31 18:09:01 -04001216 using INHERITED = ProgramVisitor;
1217 };
John Stiles92219b42020-06-15 12:32:24 -04001218
John Stilesb92641c2020-08-31 18:09:01 -04001219 return ContainsUnconditionalBreak{}.visitStatement(stmt);
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001220}
1221
John Stiles92219b42020-06-15 12:32:24 -04001222static void move_all_but_break(std::unique_ptr<Statement>& stmt,
1223 std::vector<std::unique_ptr<Statement>>* target) {
Ethan Nicholase6592142020-09-08 10:22:09 -04001224 switch (stmt->kind()) {
1225 case Statement::Kind::kBlock: {
John Stiles92219b42020-06-15 12:32:24 -04001226 // Recurse into the block.
1227 Block& block = static_cast<Block&>(*stmt);
1228
1229 std::vector<std::unique_ptr<Statement>> blockStmts;
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001230 blockStmts.reserve(block.children().size());
1231 for (std::unique_ptr<Statement>& stmt : block.children()) {
1232 move_all_but_break(stmt, &blockStmts);
Ethan Nicholas739e1ca2020-06-11 12:16:14 -04001233 }
John Stiles92219b42020-06-15 12:32:24 -04001234
1235 target->push_back(std::make_unique<Block>(block.fOffset, std::move(blockStmts),
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001236 block.symbolTable(), block.isScope()));
Ethan Nicholas739e1ca2020-06-11 12:16:14 -04001237 break;
John Stiles92219b42020-06-15 12:32:24 -04001238 }
1239
Ethan Nicholase6592142020-09-08 10:22:09 -04001240 case Statement::Kind::kBreak:
John Stiles92219b42020-06-15 12:32:24 -04001241 // Do not append a break to the target.
1242 break;
1243
Ethan Nicholas739e1ca2020-06-11 12:16:14 -04001244 default:
John Stiles92219b42020-06-15 12:32:24 -04001245 // Append normal statements to the target.
1246 target->push_back(std::move(stmt));
1247 break;
Ethan Nicholas739e1ca2020-06-11 12:16:14 -04001248 }
1249}
1250
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001251// Returns a block containing all of the statements that will be run if the given case matches
1252// (which, owing to the statements being owned by unique_ptrs, means the switch itself will be
1253// broken by this call and must then be discarded).
1254// Returns null (and leaves the switch unmodified) if no such simple reduction is possible, such as
1255// when break statements appear inside conditionals.
John Stiles92219b42020-06-15 12:32:24 -04001256static std::unique_ptr<Statement> block_for_case(SwitchStatement* switchStatement,
1257 SwitchCase* caseToCapture) {
1258 // We have to be careful to not move any of the pointers until after we're sure we're going to
1259 // succeed, so before we make any changes at all, we check the switch-cases to decide on a plan
1260 // of action. First, find the switch-case we are interested in.
1261 auto iter = switchStatement->fCases.begin();
1262 for (; iter != switchStatement->fCases.end(); ++iter) {
1263 if (iter->get() == caseToCapture) {
1264 break;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001265 }
John Stiles92219b42020-06-15 12:32:24 -04001266 }
1267
1268 // Next, walk forward through the rest of the switch. If we find a conditional break, we're
1269 // stuck and can't simplify at all. If we find an unconditional break, we have a range of
1270 // statements that we can use for simplification.
1271 auto startIter = iter;
1272 Statement* unconditionalBreakStmt = nullptr;
1273 for (; iter != switchStatement->fCases.end(); ++iter) {
1274 for (std::unique_ptr<Statement>& stmt : (*iter)->fStatements) {
1275 if (contains_conditional_break(*stmt)) {
1276 // We can't reduce switch-cases to a block when they have conditional breaks.
1277 return nullptr;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001278 }
John Stiles92219b42020-06-15 12:32:24 -04001279
1280 if (contains_unconditional_break(*stmt)) {
1281 // We found an unconditional break. We can use this block, but we need to strip
1282 // out the break statement.
1283 unconditionalBreakStmt = stmt.get();
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001284 break;
1285 }
1286 }
John Stiles92219b42020-06-15 12:32:24 -04001287
1288 if (unconditionalBreakStmt != nullptr) {
1289 break;
1290 }
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001291 }
John Stiles92219b42020-06-15 12:32:24 -04001292
1293 // We fell off the bottom of the switch or encountered a break. We know the range of statements
1294 // that we need to move over, and we know it's safe to do so.
1295 std::vector<std::unique_ptr<Statement>> caseStmts;
1296
1297 // We can move over most of the statements as-is.
1298 while (startIter != iter) {
1299 for (std::unique_ptr<Statement>& stmt : (*startIter)->fStatements) {
1300 caseStmts.push_back(std::move(stmt));
1301 }
1302 ++startIter;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001303 }
John Stiles92219b42020-06-15 12:32:24 -04001304
1305 // If we found an unconditional break at the end, we need to move what we can while avoiding
1306 // that break.
1307 if (unconditionalBreakStmt != nullptr) {
1308 for (std::unique_ptr<Statement>& stmt : (*startIter)->fStatements) {
1309 if (stmt.get() == unconditionalBreakStmt) {
1310 move_all_but_break(stmt, &caseStmts);
1311 unconditionalBreakStmt = nullptr;
1312 break;
1313 }
1314
1315 caseStmts.push_back(std::move(stmt));
1316 }
1317 }
1318
1319 SkASSERT(unconditionalBreakStmt == nullptr); // Verify that we fixed the unconditional break.
1320
1321 // Return our newly-synthesized block.
1322 return std::make_unique<Block>(/*offset=*/-1, std::move(caseStmts), switchStatement->fSymbols);
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001323}
1324
Ethan Nicholascb670962017-04-20 19:31:52 -04001325void Compiler::simplifyStatement(DefinitionMap& definitions,
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001326 BasicBlock& b,
1327 std::vector<BasicBlock::Node>::iterator* iter,
1328 std::unordered_set<const Variable*>* undefinedVariables,
1329 bool* outUpdated,
1330 bool* outNeedsRescan) {
Ethan Nicholascb670962017-04-20 19:31:52 -04001331 Statement* stmt = (*iter)->statement()->get();
Ethan Nicholase6592142020-09-08 10:22:09 -04001332 switch (stmt->kind()) {
1333 case Statement::Kind::kVarDeclaration: {
John Stilesa5a97b42020-08-18 11:19:07 -04001334 const auto& varDecl = stmt->as<VarDeclaration>();
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001335 if (varDecl.fVar->dead() &&
1336 (!varDecl.fValue ||
1337 !varDecl.fValue->hasSideEffects())) {
1338 if (varDecl.fValue) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001339 SkASSERT((*iter)->statement()->get() == stmt);
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001340 if (!b.tryRemoveExpressionBefore(iter, varDecl.fValue.get())) {
1341 *outNeedsRescan = true;
Ethan Nicholascb670962017-04-20 19:31:52 -04001342 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001343 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001344 (*iter)->setStatement(std::unique_ptr<Statement>(new Nop()));
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001345 *outUpdated = true;
Ethan Nicholascb670962017-04-20 19:31:52 -04001346 }
1347 break;
1348 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001349 case Statement::Kind::kIf: {
John Stilesa5a97b42020-08-18 11:19:07 -04001350 IfStatement& i = stmt->as<IfStatement>();
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04001351 if (i.test()->kind() == Expression::Kind::kBoolLiteral) {
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001352 // constant if, collapse down to a single branch
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04001353 if (i.test()->as<BoolLiteral>().value()) {
1354 SkASSERT(i.ifTrue());
1355 (*iter)->setStatement(std::move(i.ifTrue()));
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001356 } else {
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04001357 if (i.ifFalse()) {
1358 (*iter)->setStatement(std::move(i.ifFalse()));
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001359 } else {
1360 (*iter)->setStatement(std::unique_ptr<Statement>(new Nop()));
1361 }
1362 }
1363 *outUpdated = true;
1364 *outNeedsRescan = true;
1365 break;
1366 }
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04001367 if (i.ifFalse() && i.ifFalse()->isEmpty()) {
Ethan Nicholascb670962017-04-20 19:31:52 -04001368 // else block doesn't do anything, remove it
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04001369 i.ifFalse().reset();
Ethan Nicholascb670962017-04-20 19:31:52 -04001370 *outUpdated = true;
1371 *outNeedsRescan = true;
1372 }
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04001373 if (!i.ifFalse() && i.ifTrue()->isEmpty()) {
Ethan Nicholascb670962017-04-20 19:31:52 -04001374 // if block doesn't do anything, no else block
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04001375 if (i.test()->hasSideEffects()) {
Ethan Nicholascb670962017-04-20 19:31:52 -04001376 // test has side effects, keep it
1377 (*iter)->setStatement(std::unique_ptr<Statement>(
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04001378 new ExpressionStatement(std::move(i.test()))));
Ethan Nicholascb670962017-04-20 19:31:52 -04001379 } else {
1380 // no if, no else, no test side effects, kill the whole if
1381 // statement
1382 (*iter)->setStatement(std::unique_ptr<Statement>(new Nop()));
1383 }
1384 *outUpdated = true;
1385 *outNeedsRescan = true;
1386 }
1387 break;
1388 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001389 case Statement::Kind::kSwitch: {
John Stilesa5a97b42020-08-18 11:19:07 -04001390 SwitchStatement& s = stmt->as<SwitchStatement>();
Ethan Nicholas34b19c52020-09-14 11:33:47 -04001391 int64_t switchValue;
1392 if (fIRGenerator->getConstantInt(*s.fValue, &switchValue)) {
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001393 // switch is constant, replace it with the case that matches
1394 bool found = false;
1395 SwitchCase* defaultCase = nullptr;
John Stiles9d944232020-08-19 09:56:49 -04001396 for (const std::unique_ptr<SwitchCase>& c : s.fCases) {
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001397 if (!c->fValue) {
1398 defaultCase = c.get();
1399 continue;
1400 }
Ethan Nicholas34b19c52020-09-14 11:33:47 -04001401 int64_t caseValue;
1402 SkAssertResult(fIRGenerator->getConstantInt(*c->fValue, &caseValue));
1403 if (caseValue == switchValue) {
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001404 std::unique_ptr<Statement> newBlock = block_for_case(&s, c.get());
1405 if (newBlock) {
1406 (*iter)->setStatement(std::move(newBlock));
John Stiles9d944232020-08-19 09:56:49 -04001407 found = true;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001408 break;
1409 } else {
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -04001410 if (s.fIsStatic && !(fFlags & kPermitInvalidStaticTests_Flag)) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001411 this->error(s.fOffset,
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001412 "static switch contains non-static conditional break");
1413 s.fIsStatic = false;
1414 }
1415 return; // can't simplify
1416 }
1417 }
1418 }
1419 if (!found) {
1420 // no matching case. use default if it exists, or kill the whole thing
1421 if (defaultCase) {
1422 std::unique_ptr<Statement> newBlock = block_for_case(&s, defaultCase);
1423 if (newBlock) {
1424 (*iter)->setStatement(std::move(newBlock));
1425 } else {
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -04001426 if (s.fIsStatic && !(fFlags & kPermitInvalidStaticTests_Flag)) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001427 this->error(s.fOffset,
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001428 "static switch contains non-static conditional break");
1429 s.fIsStatic = false;
1430 }
1431 return; // can't simplify
1432 }
1433 } else {
1434 (*iter)->setStatement(std::unique_ptr<Statement>(new Nop()));
1435 }
1436 }
1437 *outUpdated = true;
1438 *outNeedsRescan = true;
1439 }
1440 break;
1441 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001442 case Statement::Kind::kExpression: {
John Stilesa5a97b42020-08-18 11:19:07 -04001443 ExpressionStatement& e = stmt->as<ExpressionStatement>();
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001444 SkASSERT((*iter)->statement()->get() == &e);
Ethan Nicholasd503a5a2020-09-30 09:29:55 -04001445 if (!e.expression()->hasSideEffects()) {
Ethan Nicholascb670962017-04-20 19:31:52 -04001446 // Expression statement with no side effects, kill it
Ethan Nicholasd503a5a2020-09-30 09:29:55 -04001447 if (!b.tryRemoveExpressionBefore(iter, e.expression().get())) {
Ethan Nicholascb670962017-04-20 19:31:52 -04001448 *outNeedsRescan = true;
1449 }
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001450 SkASSERT((*iter)->statement()->get() == stmt);
Ethan Nicholascb670962017-04-20 19:31:52 -04001451 (*iter)->setStatement(std::unique_ptr<Statement>(new Nop()));
1452 *outUpdated = true;
1453 }
1454 break;
1455 }
1456 default:
1457 break;
1458 }
1459}
1460
John Stiles0cc193a2020-09-09 09:39:34 -04001461bool Compiler::scanCFG(FunctionDefinition& f) {
1462 bool madeChanges = false;
1463
Ethan Nicholascb670962017-04-20 19:31:52 -04001464 CFG cfg = CFGGenerator().getCFG(f);
1465 this->computeDataFlow(&cfg);
ethannicholas22f939e2016-10-13 13:25:34 -07001466
1467 // check for unreachable code
1468 for (size_t i = 0; i < cfg.fBlocks.size(); i++) {
John Stiles0cc193a2020-09-09 09:39:34 -04001469 const BasicBlock& block = cfg.fBlocks[i];
John Stiles61e75e32020-10-01 15:42:37 -04001470 if (i != cfg.fStart && !block.fIsReachable && block.fNodes.size()) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001471 int offset;
John Stiles0cc193a2020-09-09 09:39:34 -04001472 const BasicBlock::Node& node = block.fNodes[0];
John Stiles70025e52020-09-28 16:08:58 -04001473 if (node.isStatement()) {
1474 offset = (*node.statement())->fOffset;
1475 } else {
1476 offset = (*node.expression())->fOffset;
1477 if ((*node.expression())->is<BoolLiteral>()) {
1478 // Function inlining can generate do { ... } while(false) loops which always
1479 // break, so the boolean condition is considered unreachable. Since not being
1480 // able to reach a literal is a non-issue in the first place, we don't report an
1481 // error in this case.
1482 continue;
1483 }
Ethan Nicholas86a43402017-01-19 13:32:00 -05001484 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001485 this->error(offset, String("unreachable"));
ethannicholas22f939e2016-10-13 13:25:34 -07001486 }
1487 }
1488 if (fErrorCount) {
John Stiles0cc193a2020-09-09 09:39:34 -04001489 return madeChanges;
ethannicholas22f939e2016-10-13 13:25:34 -07001490 }
1491
Ethan Nicholascb670962017-04-20 19:31:52 -04001492 // check for dead code & undefined variables, perform constant propagation
1493 std::unordered_set<const Variable*> undefinedVariables;
1494 bool updated;
1495 bool needsRescan = false;
1496 do {
1497 if (needsRescan) {
1498 cfg = CFGGenerator().getCFG(f);
1499 this->computeDataFlow(&cfg);
1500 needsRescan = false;
Ethan Nicholas113628d2017-02-02 16:11:39 -05001501 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001502
1503 updated = false;
Ethan Nicholas1de14812020-06-19 15:32:49 -04001504 bool first = true;
Ethan Nicholascb670962017-04-20 19:31:52 -04001505 for (BasicBlock& b : cfg.fBlocks) {
John Stiles61e75e32020-10-01 15:42:37 -04001506 if (!first && !b.fIsReachable) {
Ethan Nicholas1de14812020-06-19 15:32:49 -04001507 // Block was reachable before optimization, but has since become unreachable. In
1508 // addition to being dead code, it's broken - since control flow can't reach it, no
1509 // prior variable definitions can reach it, and therefore variables might look to
Brian Osmanc0213602020-10-06 14:43:32 -04001510 // have not been properly assigned. Kill it by replacing all statements with Nops.
Ethan Nicholas1de14812020-06-19 15:32:49 -04001511 for (BasicBlock::Node& node : b.fNodes) {
John Stiles70025e52020-09-28 16:08:58 -04001512 if (node.isStatement() && !(*node.statement())->is<Nop>()) {
John Stiles0cc193a2020-09-09 09:39:34 -04001513 node.setStatement(std::make_unique<Nop>());
1514 madeChanges = true;
Ethan Nicholas1de14812020-06-19 15:32:49 -04001515 }
1516 }
1517 continue;
1518 }
1519 first = false;
Ethan Nicholascb670962017-04-20 19:31:52 -04001520 DefinitionMap definitions = b.fBefore;
1521
1522 for (auto iter = b.fNodes.begin(); iter != b.fNodes.end() && !needsRescan; ++iter) {
John Stiles70025e52020-09-28 16:08:58 -04001523 if (iter->isExpression()) {
Ethan Nicholascb670962017-04-20 19:31:52 -04001524 this->simplifyExpression(definitions, b, &iter, &undefinedVariables, &updated,
1525 &needsRescan);
1526 } else {
1527 this->simplifyStatement(definitions, b, &iter, &undefinedVariables, &updated,
John Stiles0cc193a2020-09-09 09:39:34 -04001528 &needsRescan);
Ethan Nicholascb670962017-04-20 19:31:52 -04001529 }
Ethan Nicholas4b330df2017-05-17 10:52:55 -04001530 if (needsRescan) {
1531 break;
1532 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001533 this->addDefinitions(*iter, &definitions);
1534 }
Brian Osman01a3eb42020-09-14 11:32:49 -04001535
1536 if (needsRescan) {
1537 break;
1538 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001539 }
John Stiles0cc193a2020-09-09 09:39:34 -04001540 madeChanges |= updated;
Ethan Nicholascb670962017-04-20 19:31:52 -04001541 } while (updated);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001542 SkASSERT(!needsRescan);
ethannicholas22f939e2016-10-13 13:25:34 -07001543
Ethan Nicholas91a10532017-06-22 11:24:38 -04001544 // verify static ifs & switches, clean up dead variable decls
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001545 for (BasicBlock& b : cfg.fBlocks) {
Ethan Nicholas91a10532017-06-22 11:24:38 -04001546 for (auto iter = b.fNodes.begin(); iter != b.fNodes.end() && !needsRescan;) {
John Stiles70025e52020-09-28 16:08:58 -04001547 if (iter->isStatement()) {
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001548 const Statement& s = **iter->statement();
Ethan Nicholase6592142020-09-08 10:22:09 -04001549 switch (s.kind()) {
1550 case Statement::Kind::kIf:
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04001551 if (s.as<IfStatement>().isStatic() &&
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -04001552 !(fFlags & kPermitInvalidStaticTests_Flag)) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001553 this->error(s.fOffset, "static if has non-static test");
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001554 }
Ethan Nicholas91a10532017-06-22 11:24:38 -04001555 ++iter;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001556 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001557 case Statement::Kind::kSwitch:
John Stilesa5a97b42020-08-18 11:19:07 -04001558 if (s.as<SwitchStatement>().fIsStatic &&
John Stiles0cc193a2020-09-09 09:39:34 -04001559 !(fFlags & kPermitInvalidStaticTests_Flag)) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001560 this->error(s.fOffset, "static switch has non-static test");
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001561 }
Ethan Nicholas91a10532017-06-22 11:24:38 -04001562 ++iter;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001563 break;
1564 default:
Ethan Nicholas91a10532017-06-22 11:24:38 -04001565 ++iter;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001566 break;
1567 }
Ethan Nicholas91a10532017-06-22 11:24:38 -04001568 } else {
1569 ++iter;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001570 }
1571 }
1572 }
1573
ethannicholas22f939e2016-10-13 13:25:34 -07001574 // check for missing return
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001575 if (f.fDeclaration.fReturnType != *fContext->fVoid_Type) {
John Stiles61e75e32020-10-01 15:42:37 -04001576 if (cfg.fBlocks[cfg.fExit].fIsReachable) {
Ethan Nicholase2c49992020-10-05 11:49:11 -04001577 this->error(f.fOffset, String("function '" + String(f.fDeclaration.name()) +
Ethan Nicholasdb80f692019-11-22 14:06:12 -05001578 "' can exit without returning a value"));
ethannicholas22f939e2016-10-13 13:25:34 -07001579 }
1580 }
John Stiles0cc193a2020-09-09 09:39:34 -04001581
1582 return madeChanges;
ethannicholas22f939e2016-10-13 13:25:34 -07001583}
1584
Brian Osman32d53552020-09-23 13:55:20 -04001585std::unique_ptr<Program> Compiler::convertProgram(
1586 Program::Kind kind,
1587 String text,
1588 const Program::Settings& settings,
1589 const std::vector<std::unique_ptr<ExternalValue>>* externalValues) {
1590 SkASSERT(!externalValues || (kind == Program::kGeneric_Kind));
Ethan Nicholas91164d12019-05-15 15:29:54 -04001591
ethannicholasb3058bd2016-07-01 08:22:01 -07001592 fErrorText = "";
1593 fErrorCount = 0;
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001594 fInliner.reset(&fIRGenerator->fContext, fIRGenerator->fModifiers.get(), &settings);
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001595 std::vector<std::unique_ptr<ProgramElement>>* inherited;
ethannicholasd598f792016-07-25 10:08:54 -07001596 std::vector<std::unique_ptr<ProgramElement>> elements;
ethannicholasb3058bd2016-07-01 08:22:01 -07001597 switch (kind) {
1598 case Program::kVertex_Kind:
Brian Osmanafa18ee2020-10-07 17:47:45 -04001599 inherited = nullptr;
1600 fIRGenerator->fIntrinsics = fVertexIntrinsics.get();
1601 fIRGenerator->start(&settings, fVertexSymbolTable, /*inherited=*/nullptr);
ethannicholasb3058bd2016-07-01 08:22:01 -07001602 break;
1603 case Program::kFragment_Kind:
Brian Osman00a8b5b2020-10-02 09:06:04 -04001604 inherited = nullptr;
1605 fIRGenerator->fIntrinsics = fFragmentIntrinsics.get();
1606 fIRGenerator->start(&settings, fFragmentSymbolTable, /*inherited=*/nullptr);
ethannicholasb3058bd2016-07-01 08:22:01 -07001607 break;
Ethan Nicholas52cad152017-02-16 16:37:32 -05001608 case Program::kGeometry_Kind:
Ethan Nicholasc18bb512020-07-28 14:46:53 -04001609 this->loadGeometryIntrinsics();
Brian Osmanafa18ee2020-10-07 17:47:45 -04001610 inherited = nullptr;
1611 fIRGenerator->fIntrinsics = fGeometryIntrinsics.get();
1612 fIRGenerator->start(&settings, fGeometrySymbolTable, /*inherited=*/nullptr);
Ethan Nicholas52cad152017-02-16 16:37:32 -05001613 break;
Brian Osman8e2ef022020-09-30 13:26:43 -04001614 case Program::kFragmentProcessor_Kind:
1615 this->loadFPIntrinsics();
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001616 inherited = nullptr;
Brian Osman8e2ef022020-09-30 13:26:43 -04001617 fIRGenerator->fIntrinsics = fFPIntrinsics.get();
1618 fIRGenerator->start(&settings, fFPSymbolTable, /*inherited=*/nullptr);
Ethan Nicholas762466e2017-06-29 10:03:38 -04001619 break;
Ethan Nicholas8da1e652019-05-24 11:01:59 -04001620 case Program::kPipelineStage_Kind:
Ethan Nicholasc18bb512020-07-28 14:46:53 -04001621 this->loadPipelineIntrinsics();
Brian Osman8e2ef022020-09-30 13:26:43 -04001622 inherited = nullptr;
1623 fIRGenerator->fIntrinsics = fPipelineIntrinsics.get();
1624 fIRGenerator->start(&settings, fPipelineSymbolTable, /*inherited=*/nullptr);
Ethan Nicholas8da1e652019-05-24 11:01:59 -04001625 break;
Ethan Nicholas746035a2019-04-23 13:31:09 -04001626 case Program::kGeneric_Kind:
Ethan Nicholasc18bb512020-07-28 14:46:53 -04001627 this->loadInterpreterIntrinsics();
Brian Osmaneac49832020-09-18 11:49:22 -04001628 inherited = nullptr;
John Stiles810c8cf2020-08-26 19:46:27 -04001629 fIRGenerator->fIntrinsics = fInterpreterIntrinsics.get();
Brian Osmane498b3c2020-09-23 14:42:11 -04001630 fIRGenerator->start(&settings, fInterpreterSymbolTable, /*inherited=*/nullptr);
Ethan Nicholas0d997662019-04-08 09:46:01 -04001631 break;
ethannicholasb3058bd2016-07-01 08:22:01 -07001632 }
Brian Osman32d53552020-09-23 13:55:20 -04001633 if (externalValues) {
1634 // Add any external values to the symbol table. IRGenerator::start() has pushed a table, so
1635 // we're only making these visible to the current Program.
1636 for (const auto& ev : *externalValues) {
John Stilesb8cc6652020-10-08 09:12:07 -04001637 fIRGenerator->fSymbolTable->addWithoutOwnership(ev.get());
Brian Osman32d53552020-09-23 13:55:20 -04001638 }
1639 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001640 std::unique_ptr<String> textPtr(new String(std::move(text)));
1641 fSource = textPtr.get();
Ethan Nicholasc18bb512020-07-28 14:46:53 -04001642 fIRGenerator->convertProgram(kind, textPtr->c_str(), textPtr->size(), &elements);
John Stilesfbd050b2020-08-03 13:21:46 -04001643 auto result = std::make_unique<Program>(kind,
1644 std::move(textPtr),
1645 settings,
1646 fContext,
1647 inherited,
1648 std::move(elements),
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001649 fIRGenerator->releaseModifiers(),
John Stilesfbd050b2020-08-03 13:21:46 -04001650 fIRGenerator->fSymbolTable,
1651 fIRGenerator->fInputs);
Brian Osmane498b3c2020-09-23 14:42:11 -04001652 fIRGenerator->finish();
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001653 if (fErrorCount) {
1654 return nullptr;
1655 }
Ethan Nicholas34b19c52020-09-14 11:33:47 -04001656 if (settings.fOptimize && !this->optimize(*result)) {
1657 return nullptr;
1658 }
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001659 return result;
1660}
1661
Ethan Nicholas00543112018-07-31 09:44:36 -04001662bool Compiler::optimize(Program& program) {
1663 SkASSERT(!fErrorCount);
Ethan Nicholas34b19c52020-09-14 11:33:47 -04001664 fIRGenerator->fKind = program.fKind;
1665 fIRGenerator->fSettings = &program.fSettings;
John Stiles7954d6c2020-09-01 10:53:02 -04001666
Ethan Nicholas34b19c52020-09-14 11:33:47 -04001667 while (fErrorCount == 0) {
1668 bool madeChanges = false;
John Stiles7954d6c2020-09-01 10:53:02 -04001669
Ethan Nicholas34b19c52020-09-14 11:33:47 -04001670 // Scan and optimize based on the control-flow graph for each function.
1671 for (ProgramElement& element : program) {
1672 if (element.is<FunctionDefinition>()) {
1673 madeChanges |= this->scanCFG(element.as<FunctionDefinition>());
1674 }
1675 }
1676
1677 // Perform inline-candidate analysis and inline any functions deemed suitable.
John Stiles881a10c2020-09-19 10:13:24 -04001678 madeChanges |= fInliner.analyze(program);
Ethan Nicholas34b19c52020-09-14 11:33:47 -04001679
1680 // Remove dead functions. We wait until after analysis so that we still report errors,
1681 // even in unused code.
1682 if (program.fSettings.fRemoveDeadFunctions) {
1683 program.fElements.erase(
1684 std::remove_if(program.fElements.begin(),
1685 program.fElements.end(),
1686 [&](const std::unique_ptr<ProgramElement>& element) {
1687 if (!element->is<FunctionDefinition>()) {
1688 return false;
1689 }
1690 const auto& fn = element->as<FunctionDefinition>();
1691 bool dead = fn.fDeclaration.fCallCount == 0 &&
Ethan Nicholase2c49992020-10-05 11:49:11 -04001692 fn.fDeclaration.name() != "main";
Ethan Nicholas34b19c52020-09-14 11:33:47 -04001693 madeChanges |= dead;
1694 return dead;
1695 }),
1696 program.fElements.end());
1697 }
1698
1699 if (program.fKind != Program::kFragmentProcessor_Kind) {
Brian Osmanc0213602020-10-06 14:43:32 -04001700 // Remove declarations of dead global variables
Ethan Nicholas34b19c52020-09-14 11:33:47 -04001701 program.fElements.erase(
1702 std::remove_if(program.fElements.begin(), program.fElements.end(),
1703 [&](const std::unique_ptr<ProgramElement>& element) {
Brian Osmanc0213602020-10-06 14:43:32 -04001704 if (!element->is<GlobalVarDeclaration>()) {
Ethan Nicholas34b19c52020-09-14 11:33:47 -04001705 return false;
1706 }
Brian Osmanc0213602020-10-06 14:43:32 -04001707 const auto& varDecl = element->as<GlobalVarDeclaration>();
1708 bool dead = varDecl.fDecl->fVar->dead();
Ethan Nicholas34b19c52020-09-14 11:33:47 -04001709 madeChanges |= dead;
1710 return dead;
1711 }),
1712 program.fElements.end());
1713 }
John Stiles73a6bff2020-09-09 13:40:37 -04001714
Ethan Nicholas34b19c52020-09-14 11:33:47 -04001715 if (!madeChanges) {
1716 break;
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001717 }
Ethan Nicholas00543112018-07-31 09:44:36 -04001718 }
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001719 program.finish();
Ethan Nicholas00543112018-07-31 09:44:36 -04001720 return fErrorCount == 0;
1721}
1722
Brian Osmanfb32ddf2019-06-18 10:14:20 -04001723#if defined(SKSL_STANDALONE) || SK_SUPPORT_GPU
1724
Ethan Nicholas00543112018-07-31 09:44:36 -04001725bool Compiler::toSPIRV(Program& program, OutputStream& out) {
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001726#ifdef SK_ENABLE_SPIRV_VALIDATION
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001727 StringStream buffer;
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001728 fSource = program.fSource.get();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001729 SPIRVCodeGenerator cg(&fIRGenerator->fContext, fIRGenerator->fModifiers.get(), &program, this,
1730 &buffer);
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001731 bool result = cg.generateCode();
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001732 fSource = nullptr;
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001733 if (result) {
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001734 spvtools::SpirvTools tools(SPV_ENV_VULKAN_1_0);
Ethan Nicholas762466e2017-06-29 10:03:38 -04001735 const String& data = buffer.str();
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001736 SkASSERT(0 == data.size() % 4);
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001737 auto dumpmsg = [](spv_message_level_t, const char*, const spv_position_t&, const char* m) {
1738 SkDebugf("SPIR-V validation error: %s\n", m);
1739 };
1740 tools.SetMessageConsumer(dumpmsg);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001741 // Verify that the SPIR-V we produced is valid. If this SkASSERT fails, check the logs prior
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001742 // to the failure to see the validation errors.
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001743 SkAssertResult(tools.Validate((const uint32_t*) data.c_str(), data.size() / 4));
Ethan Nicholas762466e2017-06-29 10:03:38 -04001744 out.write(data.c_str(), data.size());
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001745 }
1746#else
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001747 fSource = program.fSource.get();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001748 SPIRVCodeGenerator cg(&fIRGenerator->fContext, fIRGenerator->fModifiers.get(), &program, this,
1749 &out);
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001750 bool result = cg.generateCode();
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001751 fSource = nullptr;
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001752#endif
Ethan Nicholasce33f102016-12-09 17:22:59 -05001753 return result;
1754}
1755
Ethan Nicholas00543112018-07-31 09:44:36 -04001756bool Compiler::toSPIRV(Program& program, String* out) {
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001757 StringStream buffer;
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001758 bool result = this->toSPIRV(program, buffer);
1759 if (result) {
Ethan Nicholas762466e2017-06-29 10:03:38 -04001760 *out = buffer.str();
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001761 }
1762 return result;
1763}
1764
Ethan Nicholas00543112018-07-31 09:44:36 -04001765bool Compiler::toGLSL(Program& program, OutputStream& out) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001766 fSource = program.fSource.get();
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001767 GLSLCodeGenerator cg(fContext.get(), &program, this, &out);
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001768 bool result = cg.generateCode();
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001769 fSource = nullptr;
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001770 return result;
1771}
1772
Ethan Nicholas00543112018-07-31 09:44:36 -04001773bool Compiler::toGLSL(Program& program, String* out) {
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001774 StringStream buffer;
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001775 bool result = this->toGLSL(program, buffer);
1776 if (result) {
Ethan Nicholas762466e2017-06-29 10:03:38 -04001777 *out = buffer.str();
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001778 }
1779 return result;
1780}
1781
Brian Osmanc0243912020-02-19 15:35:26 -05001782bool Compiler::toHLSL(Program& program, String* out) {
1783 String spirv;
1784 if (!this->toSPIRV(program, &spirv)) {
1785 return false;
1786 }
1787
1788 return SPIRVtoHLSL(spirv, out);
1789}
1790
Ethan Nicholas00543112018-07-31 09:44:36 -04001791bool Compiler::toMetal(Program& program, OutputStream& out) {
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001792 MetalCodeGenerator cg(fContext.get(), &program, this, &out);
Ethan Nicholascc305772017-10-13 16:17:45 -04001793 bool result = cg.generateCode();
Ethan Nicholascc305772017-10-13 16:17:45 -04001794 return result;
1795}
1796
Ethan Nicholas00543112018-07-31 09:44:36 -04001797bool Compiler::toMetal(Program& program, String* out) {
Timothy Liangb8eeb802018-07-23 16:46:16 -04001798 StringStream buffer;
1799 bool result = this->toMetal(program, buffer);
1800 if (result) {
1801 *out = buffer.str();
1802 }
1803 return result;
1804}
1805
Greg Daniela28ea672020-09-25 11:12:56 -04001806#if defined(SKSL_STANDALONE) || GR_TEST_UTILS
Ethan Nicholas00543112018-07-31 09:44:36 -04001807bool Compiler::toCPP(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 CPPCodeGenerator 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 Nicholas762466e2017-06-29 10:03:38 -04001812 return result;
1813}
1814
Ethan Nicholas00543112018-07-31 09:44:36 -04001815bool Compiler::toH(Program& program, String name, OutputStream& out) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001816 fSource = program.fSource.get();
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001817 HCodeGenerator cg(fContext.get(), &program, this, name, &out);
Ethan Nicholas762466e2017-06-29 10:03:38 -04001818 bool result = cg.generateCode();
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001819 fSource = nullptr;
Ethan Nicholas00543112018-07-31 09:44:36 -04001820 return result;
1821}
Greg Daniela28ea672020-09-25 11:12:56 -04001822#endif // defined(SKSL_STANDALONE) || GR_TEST_UTILS
Ethan Nicholas00543112018-07-31 09:44:36 -04001823
Ethan Nicholas2a479a52020-08-18 16:29:45 -04001824#endif // defined(SKSL_STANDALONE) || SK_SUPPORT_GPU
Brian Osman2e29ab52019-09-20 12:19:11 -04001825
1826#if !defined(SKSL_STANDALONE) && SK_SUPPORT_GPU
Brian Osmana4b91692020-08-10 14:26:16 -04001827bool Compiler::toPipelineStage(Program& program, PipelineStageArgs* outArgs) {
Ethan Nicholas00543112018-07-31 09:44:36 -04001828 fSource = program.fSource.get();
1829 StringStream buffer;
Brian Osman300fe1d2020-01-23 15:42:43 -05001830 PipelineStageCodeGenerator cg(fContext.get(), &program, this, &buffer, outArgs);
Ethan Nicholas00543112018-07-31 09:44:36 -04001831 bool result = cg.generateCode();
1832 fSource = nullptr;
1833 if (result) {
Brian Osman107c6662019-12-30 15:02:30 -05001834 outArgs->fCode = buffer.str();
Ethan Nicholas00543112018-07-31 09:44:36 -04001835 }
Ethan Nicholas762466e2017-06-29 10:03:38 -04001836 return result;
1837}
Brian Osmanfb32ddf2019-06-18 10:14:20 -04001838#endif
1839
Ethan Nicholas0e9401d2019-03-21 11:05:37 -04001840std::unique_ptr<ByteCode> Compiler::toByteCode(Program& program) {
Mike Klein853d4ed2020-08-20 00:41:00 +00001841#if defined(SK_ENABLE_SKSL_INTERPRETER)
Brian Osman808f0212020-01-21 15:36:47 -05001842 fSource = program.fSource.get();
Ethan Nicholas0e9401d2019-03-21 11:05:37 -04001843 std::unique_ptr<ByteCode> result(new ByteCode());
Brian Osmanb08cc022020-04-02 11:38:40 -04001844 ByteCodeGenerator cg(fContext.get(), &program, this, result.get());
1845 bool success = cg.generateCode();
1846 fSource = nullptr;
1847 if (success) {
Ethan Nicholas0e9401d2019-03-21 11:05:37 -04001848 return result;
1849 }
Mike Klein853d4ed2020-08-20 00:41:00 +00001850#else
1851 ABORT("ByteCode interpreter not enabled");
1852#endif
Ethan Nicholas0e9401d2019-03-21 11:05:37 -04001853 return nullptr;
1854}
1855
Brian Osman401a0092020-09-10 14:47:24 -04001856const char* Compiler::OperatorName(Token::Kind op) {
1857 switch (op) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001858 case Token::Kind::TK_PLUS: return "+";
1859 case Token::Kind::TK_MINUS: return "-";
1860 case Token::Kind::TK_STAR: return "*";
1861 case Token::Kind::TK_SLASH: return "/";
1862 case Token::Kind::TK_PERCENT: return "%";
1863 case Token::Kind::TK_SHL: return "<<";
1864 case Token::Kind::TK_SHR: return ">>";
1865 case Token::Kind::TK_LOGICALNOT: return "!";
1866 case Token::Kind::TK_LOGICALAND: return "&&";
1867 case Token::Kind::TK_LOGICALOR: return "||";
1868 case Token::Kind::TK_LOGICALXOR: return "^^";
1869 case Token::Kind::TK_BITWISENOT: return "~";
1870 case Token::Kind::TK_BITWISEAND: return "&";
1871 case Token::Kind::TK_BITWISEOR: return "|";
1872 case Token::Kind::TK_BITWISEXOR: return "^";
1873 case Token::Kind::TK_EQ: return "=";
1874 case Token::Kind::TK_EQEQ: return "==";
1875 case Token::Kind::TK_NEQ: return "!=";
1876 case Token::Kind::TK_LT: return "<";
1877 case Token::Kind::TK_GT: return ">";
1878 case Token::Kind::TK_LTEQ: return "<=";
1879 case Token::Kind::TK_GTEQ: return ">=";
1880 case Token::Kind::TK_PLUSEQ: return "+=";
1881 case Token::Kind::TK_MINUSEQ: return "-=";
1882 case Token::Kind::TK_STAREQ: return "*=";
1883 case Token::Kind::TK_SLASHEQ: return "/=";
1884 case Token::Kind::TK_PERCENTEQ: return "%=";
1885 case Token::Kind::TK_SHLEQ: return "<<=";
1886 case Token::Kind::TK_SHREQ: return ">>=";
1887 case Token::Kind::TK_LOGICALANDEQ: return "&&=";
1888 case Token::Kind::TK_LOGICALOREQ: return "||=";
1889 case Token::Kind::TK_LOGICALXOREQ: return "^^=";
1890 case Token::Kind::TK_BITWISEANDEQ: return "&=";
1891 case Token::Kind::TK_BITWISEOREQ: return "|=";
1892 case Token::Kind::TK_BITWISEXOREQ: return "^=";
1893 case Token::Kind::TK_PLUSPLUS: return "++";
1894 case Token::Kind::TK_MINUSMINUS: return "--";
1895 case Token::Kind::TK_COMMA: return ",";
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001896 default:
Brian Osman401a0092020-09-10 14:47:24 -04001897 ABORT("unsupported operator: %d\n", (int) op);
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001898 }
1899}
1900
1901
1902bool Compiler::IsAssignment(Token::Kind op) {
1903 switch (op) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001904 case Token::Kind::TK_EQ: // fall through
1905 case Token::Kind::TK_PLUSEQ: // fall through
1906 case Token::Kind::TK_MINUSEQ: // fall through
1907 case Token::Kind::TK_STAREQ: // fall through
1908 case Token::Kind::TK_SLASHEQ: // fall through
1909 case Token::Kind::TK_PERCENTEQ: // fall through
1910 case Token::Kind::TK_SHLEQ: // fall through
1911 case Token::Kind::TK_SHREQ: // fall through
1912 case Token::Kind::TK_BITWISEOREQ: // fall through
1913 case Token::Kind::TK_BITWISEXOREQ: // fall through
1914 case Token::Kind::TK_BITWISEANDEQ: // fall through
1915 case Token::Kind::TK_LOGICALOREQ: // fall through
1916 case Token::Kind::TK_LOGICALXOREQ: // fall through
1917 case Token::Kind::TK_LOGICALANDEQ:
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001918 return true;
1919 default:
1920 return false;
1921 }
1922}
1923
Brian Osman401a0092020-09-10 14:47:24 -04001924Token::Kind Compiler::RemoveAssignment(Token::Kind op) {
1925 switch (op) {
1926 case Token::Kind::TK_PLUSEQ: return Token::Kind::TK_PLUS;
1927 case Token::Kind::TK_MINUSEQ: return Token::Kind::TK_MINUS;
1928 case Token::Kind::TK_STAREQ: return Token::Kind::TK_STAR;
1929 case Token::Kind::TK_SLASHEQ: return Token::Kind::TK_SLASH;
1930 case Token::Kind::TK_PERCENTEQ: return Token::Kind::TK_PERCENT;
1931 case Token::Kind::TK_SHLEQ: return Token::Kind::TK_SHL;
1932 case Token::Kind::TK_SHREQ: return Token::Kind::TK_SHR;
1933 case Token::Kind::TK_BITWISEOREQ: return Token::Kind::TK_BITWISEOR;
1934 case Token::Kind::TK_BITWISEXOREQ: return Token::Kind::TK_BITWISEXOR;
1935 case Token::Kind::TK_BITWISEANDEQ: return Token::Kind::TK_BITWISEAND;
1936 case Token::Kind::TK_LOGICALOREQ: return Token::Kind::TK_LOGICALOR;
1937 case Token::Kind::TK_LOGICALXOREQ: return Token::Kind::TK_LOGICALXOR;
1938 case Token::Kind::TK_LOGICALANDEQ: return Token::Kind::TK_LOGICALAND;
1939 default: return op;
1940 }
1941}
1942
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001943Position Compiler::position(int offset) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001944 SkASSERT(fSource);
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001945 int line = 1;
1946 int column = 1;
1947 for (int i = 0; i < offset; i++) {
1948 if ((*fSource)[i] == '\n') {
1949 ++line;
1950 column = 1;
1951 }
1952 else {
1953 ++column;
1954 }
1955 }
1956 return Position(line, column);
1957}
1958
1959void Compiler::error(int offset, String msg) {
ethannicholasb3058bd2016-07-01 08:22:01 -07001960 fErrorCount++;
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001961 Position pos = this->position(offset);
1962 fErrorText += "error: " + to_string(pos.fLine) + ": " + msg.c_str() + "\n";
ethannicholasb3058bd2016-07-01 08:22:01 -07001963}
1964
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001965String Compiler::errorText() {
Ethan Nicholas00543112018-07-31 09:44:36 -04001966 this->writeErrorCount();
1967 fErrorCount = 0;
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001968 String result = fErrorText;
ethannicholasb3058bd2016-07-01 08:22:01 -07001969 return result;
1970}
1971
1972void Compiler::writeErrorCount() {
1973 if (fErrorCount) {
1974 fErrorText += to_string(fErrorCount) + " error";
1975 if (fErrorCount > 1) {
1976 fErrorText += "s";
1977 }
1978 fErrorText += "\n";
1979 }
1980}
1981
John Stilesa6841be2020-08-06 14:11:56 -04001982} // namespace SkSL