blob: 27ff41cd2d55ceb706bfae87bbbe0a04eaf86f62 [file] [log] [blame]
ethannicholasb3058bd2016-07-01 08:22:01 -07001/*
2 * Copyright 2016 Google Inc.
3 *
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
6 */
Mike Klein6ad99092016-10-26 10:35:22 -04007
Mike Kleinc0bd9f92019-04-23 12:05:21 -05008#include "src/sksl/SkSLCompiler.h"
ethannicholasb3058bd2016-07-01 08:22:01 -07009
John Stilesfbd050b2020-08-03 13:21:46 -040010#include <memory>
John Stilesb8e010c2020-08-11 18:05:39 -040011#include <unordered_set>
John Stilesfbd050b2020-08-03 13:21:46 -040012
John Stilesb92641c2020-08-31 18:09:01 -040013#include "src/sksl/SkSLAnalysis.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050014#include "src/sksl/SkSLByteCodeGenerator.h"
15#include "src/sksl/SkSLCFGGenerator.h"
16#include "src/sksl/SkSLCPPCodeGenerator.h"
17#include "src/sksl/SkSLGLSLCodeGenerator.h"
18#include "src/sksl/SkSLHCodeGenerator.h"
19#include "src/sksl/SkSLIRGenerator.h"
20#include "src/sksl/SkSLMetalCodeGenerator.h"
21#include "src/sksl/SkSLPipelineStageCodeGenerator.h"
Ethan Nicholasc18bb512020-07-28 14:46:53 -040022#include "src/sksl/SkSLRehydrator.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050023#include "src/sksl/SkSLSPIRVCodeGenerator.h"
Brian Osmanc0243912020-02-19 15:35:26 -050024#include "src/sksl/SkSLSPIRVtoHLSL.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050025#include "src/sksl/ir/SkSLEnum.h"
26#include "src/sksl/ir/SkSLExpression.h"
27#include "src/sksl/ir/SkSLExpressionStatement.h"
28#include "src/sksl/ir/SkSLFunctionCall.h"
29#include "src/sksl/ir/SkSLIntLiteral.h"
30#include "src/sksl/ir/SkSLModifiersDeclaration.h"
31#include "src/sksl/ir/SkSLNop.h"
32#include "src/sksl/ir/SkSLSymbolTable.h"
33#include "src/sksl/ir/SkSLTernaryExpression.h"
34#include "src/sksl/ir/SkSLUnresolvedFunction.h"
35#include "src/sksl/ir/SkSLVarDeclarations.h"
John Stilese6150002020-10-05 12:03:53 -040036#include "src/utils/SkBitSet.h"
ethannicholasb3058bd2016-07-01 08:22:01 -070037
Ethan Nicholasb33fa3f2020-08-06 13:00:19 -040038#include <fstream>
39
Ethan Nicholasa11035b2019-11-26 16:27:47 -050040#if !defined(SKSL_STANDALONE) & SK_SUPPORT_GPU
41#include "include/gpu/GrContextOptions.h"
42#include "src/gpu/GrShaderCaps.h"
43#endif
44
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -040045#ifdef SK_ENABLE_SPIRV_VALIDATION
46#include "spirv-tools/libspirv.hpp"
47#endif
48
Brian Osmandd496172020-08-08 08:17:18 -040049#if !SKSL_STANDALONE
Ethan Nicholasc18bb512020-07-28 14:46:53 -040050
51#include "src/sksl/generated/sksl_fp.dehydrated.sksl"
52#include "src/sksl/generated/sksl_frag.dehydrated.sksl"
53#include "src/sksl/generated/sksl_geom.dehydrated.sksl"
54#include "src/sksl/generated/sksl_gpu.dehydrated.sksl"
55#include "src/sksl/generated/sksl_interp.dehydrated.sksl"
56#include "src/sksl/generated/sksl_pipeline.dehydrated.sksl"
57#include "src/sksl/generated/sksl_vert.dehydrated.sksl"
58
59#else
60
Brian Osmandd496172020-08-08 08:17:18 -040061// GN generates or copies all of these files to the skslc executable directory
62static const char SKSL_GPU_INCLUDE[] = "sksl_gpu.sksl";
63static const char SKSL_INTERP_INCLUDE[] = "sksl_interp.sksl";
64static const char SKSL_VERT_INCLUDE[] = "sksl_vert.sksl";
65static const char SKSL_FRAG_INCLUDE[] = "sksl_frag.sksl";
66static const char SKSL_GEOM_INCLUDE[] = "sksl_geom.sksl";
67static const char SKSL_FP_INCLUDE[] = "sksl_fp.sksl";
68static const char SKSL_PIPELINE_INCLUDE[] = "sksl_pipeline.sksl";
Ethan Nicholasc18bb512020-07-28 14:46:53 -040069
70#endif
Ethan Nicholas0d997662019-04-08 09:46:01 -040071
ethannicholasb3058bd2016-07-01 08:22:01 -070072namespace SkSL {
73
Ethan Nicholasdb80f692019-11-22 14:06:12 -050074static void grab_intrinsics(std::vector<std::unique_ptr<ProgramElement>>* src,
John Stiles810c8cf2020-08-26 19:46:27 -040075 IRIntrinsicMap* target) {
Brian Osman08f986d2020-05-13 17:06:46 -040076 for (auto iter = src->begin(); iter != src->end(); ) {
77 std::unique_ptr<ProgramElement>& element = *iter;
Ethan Nicholase6592142020-09-08 10:22:09 -040078 switch (element->kind()) {
79 case ProgramElement::Kind::kFunction: {
John Stiles3dc0da62020-08-19 17:48:31 -040080 FunctionDefinition& f = element->as<FunctionDefinition>();
Brian Osman08f986d2020-05-13 17:06:46 -040081 SkASSERT(f.fDeclaration.fBuiltin);
Brian Osman2b469eb2020-09-21 11:32:10 -040082 target->insertOrDie(f.fDeclaration.description(), std::move(element));
Brian Osman08f986d2020-05-13 17:06:46 -040083 iter = src->erase(iter);
Ethan Nicholasdb80f692019-11-22 14:06:12 -050084 break;
85 }
Ethan Nicholase6592142020-09-08 10:22:09 -040086 case ProgramElement::Kind::kEnum: {
John Stiles3dc0da62020-08-19 17:48:31 -040087 Enum& e = element->as<Enum>();
Ethan Nicholasd83ded82020-09-29 17:05:54 -040088 target->insertOrDie(e.typeName(), std::move(element));
Brian Osman08f986d2020-05-13 17:06:46 -040089 iter = src->erase(iter);
Ethan Nicholasdb80f692019-11-22 14:06:12 -050090 break;
91 }
Brian Osman8e2ef022020-09-30 13:26:43 -040092 case ProgramElement::Kind::kVar: {
93 // TODO: For now, we only support one variable per declaration. We map names to
94 // declarations, and each declaration pulls in all of it's variables, so this rule
95 // ensures that we never pull in variables that aren't actually used.
96 const VarDeclarations& vd = element->as<VarDeclarations>();
97 SkASSERT(vd.fVars.size() == 1);
98 const Variable* var = vd.fVars[0]->as<VarDeclaration>().fVar;
Brian Osman58384ad2020-10-02 22:15:22 +000099 target->insertOrDie(var->fName, std::move(element));
Brian Osman8e2ef022020-09-30 13:26:43 -0400100 iter = src->erase(iter);
101 break;
102 }
Ethan Nicholasdb80f692019-11-22 14:06:12 -0500103 default:
Brian Osman00a8b5b2020-10-02 09:06:04 -0400104 printf("Unsupported element: %s\n", element->description().c_str());
105 SkASSERT(false);
Brian Osman2b469eb2020-09-21 11:32:10 -0400106 break;
Ethan Nicholasdb80f692019-11-22 14:06:12 -0500107 }
108 }
109}
110
John Stilesbc0c29e2020-09-28 13:13:40 -0400111static void reset_call_counts(std::vector<std::unique_ptr<ProgramElement>>* src) {
112 for (std::unique_ptr<ProgramElement>& element : *src) {
113 if (element->is<FunctionDefinition>()) {
114 const FunctionDeclaration& fnDecl = element->as<FunctionDefinition>().fDeclaration;
115 fnDecl.fCallCount = 0;
116 }
117 }
118}
119
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -0400120Compiler::Compiler(Flags flags)
Brian Osman00a8b5b2020-10-02 09:06:04 -0400121: fFlags(flags)
John Stiles810c8cf2020-08-26 19:46:27 -0400122, fContext(std::make_shared<Context>())
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -0400123, fErrorCount(0) {
Brian Osmaneac49832020-09-18 11:49:22 -0400124 fRootSymbolTable = std::make_shared<SymbolTable>(this);
John Stiles941fc712020-09-19 12:47:10 +0000125 fIRGenerator =
126 std::make_unique<IRGenerator>(fContext.get(), &fInliner, fRootSymbolTable, *this);
Brian Osman58384ad2020-10-02 22:15:22 +0000127 #define ADD_TYPE(t) fRootSymbolTable->addWithoutOwnership(fContext->f ## t ## _Type->fName, \
Brian Osmaneac49832020-09-18 11:49:22 -0400128 fContext->f ## t ## _Type.get())
ethannicholasb3058bd2016-07-01 08:22:01 -0700129 ADD_TYPE(Void);
130 ADD_TYPE(Float);
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400131 ADD_TYPE(Float2);
132 ADD_TYPE(Float3);
133 ADD_TYPE(Float4);
Ethan Nicholasdcba08e2017-08-02 10:52:54 -0400134 ADD_TYPE(Half);
135 ADD_TYPE(Half2);
136 ADD_TYPE(Half3);
137 ADD_TYPE(Half4);
ethannicholasb3058bd2016-07-01 08:22:01 -0700138 ADD_TYPE(Int);
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400139 ADD_TYPE(Int2);
140 ADD_TYPE(Int3);
141 ADD_TYPE(Int4);
ethannicholasb3058bd2016-07-01 08:22:01 -0700142 ADD_TYPE(UInt);
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400143 ADD_TYPE(UInt2);
144 ADD_TYPE(UInt3);
145 ADD_TYPE(UInt4);
Ethan Nicholasdcba08e2017-08-02 10:52:54 -0400146 ADD_TYPE(Short);
147 ADD_TYPE(Short2);
148 ADD_TYPE(Short3);
149 ADD_TYPE(Short4);
150 ADD_TYPE(UShort);
151 ADD_TYPE(UShort2);
152 ADD_TYPE(UShort3);
153 ADD_TYPE(UShort4);
Ruiqi Maob609e6d2018-07-17 10:19:38 -0400154 ADD_TYPE(Byte);
155 ADD_TYPE(Byte2);
156 ADD_TYPE(Byte3);
157 ADD_TYPE(Byte4);
158 ADD_TYPE(UByte);
159 ADD_TYPE(UByte2);
160 ADD_TYPE(UByte3);
161 ADD_TYPE(UByte4);
ethannicholasb3058bd2016-07-01 08:22:01 -0700162 ADD_TYPE(Bool);
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400163 ADD_TYPE(Bool2);
164 ADD_TYPE(Bool3);
165 ADD_TYPE(Bool4);
166 ADD_TYPE(Float2x2);
167 ADD_TYPE(Float2x3);
168 ADD_TYPE(Float2x4);
169 ADD_TYPE(Float3x2);
170 ADD_TYPE(Float3x3);
171 ADD_TYPE(Float3x4);
172 ADD_TYPE(Float4x2);
173 ADD_TYPE(Float4x3);
174 ADD_TYPE(Float4x4);
Ethan Nicholasdcba08e2017-08-02 10:52:54 -0400175 ADD_TYPE(Half2x2);
176 ADD_TYPE(Half2x3);
177 ADD_TYPE(Half2x4);
178 ADD_TYPE(Half3x2);
179 ADD_TYPE(Half3x3);
180 ADD_TYPE(Half3x4);
181 ADD_TYPE(Half4x2);
182 ADD_TYPE(Half4x3);
183 ADD_TYPE(Half4x4);
ethannicholasb3058bd2016-07-01 08:22:01 -0700184 ADD_TYPE(GenType);
Ethan Nicholasdcba08e2017-08-02 10:52:54 -0400185 ADD_TYPE(GenHType);
ethannicholasb3058bd2016-07-01 08:22:01 -0700186 ADD_TYPE(GenIType);
187 ADD_TYPE(GenUType);
188 ADD_TYPE(GenBType);
189 ADD_TYPE(Mat);
190 ADD_TYPE(Vec);
191 ADD_TYPE(GVec);
192 ADD_TYPE(GVec2);
193 ADD_TYPE(GVec3);
194 ADD_TYPE(GVec4);
Ethan Nicholasdcba08e2017-08-02 10:52:54 -0400195 ADD_TYPE(HVec);
ethannicholasb3058bd2016-07-01 08:22:01 -0700196 ADD_TYPE(IVec);
197 ADD_TYPE(UVec);
Ethan Nicholasdcba08e2017-08-02 10:52:54 -0400198 ADD_TYPE(SVec);
199 ADD_TYPE(USVec);
Ruiqi Maob609e6d2018-07-17 10:19:38 -0400200 ADD_TYPE(ByteVec);
201 ADD_TYPE(UByteVec);
ethannicholasb3058bd2016-07-01 08:22:01 -0700202 ADD_TYPE(BVec);
203
204 ADD_TYPE(Sampler1D);
205 ADD_TYPE(Sampler2D);
206 ADD_TYPE(Sampler3D);
ethannicholas5961bc92016-10-12 06:39:56 -0700207 ADD_TYPE(SamplerExternalOES);
ethannicholasb3058bd2016-07-01 08:22:01 -0700208 ADD_TYPE(SamplerCube);
209 ADD_TYPE(Sampler2DRect);
210 ADD_TYPE(Sampler1DArray);
211 ADD_TYPE(Sampler2DArray);
212 ADD_TYPE(SamplerCubeArray);
213 ADD_TYPE(SamplerBuffer);
214 ADD_TYPE(Sampler2DMS);
215 ADD_TYPE(Sampler2DMSArray);
216
Brian Salomonbf7b6202016-11-11 16:08:03 -0500217 ADD_TYPE(ISampler2D);
218
Brian Salomon2a51de82016-11-16 12:06:01 -0500219 ADD_TYPE(Image2D);
220 ADD_TYPE(IImage2D);
221
Greg Daniel64773e62016-11-22 09:44:03 -0500222 ADD_TYPE(SubpassInput);
223 ADD_TYPE(SubpassInputMS);
224
ethannicholasb3058bd2016-07-01 08:22:01 -0700225 ADD_TYPE(GSampler1D);
226 ADD_TYPE(GSampler2D);
227 ADD_TYPE(GSampler3D);
228 ADD_TYPE(GSamplerCube);
229 ADD_TYPE(GSampler2DRect);
230 ADD_TYPE(GSampler1DArray);
231 ADD_TYPE(GSampler2DArray);
232 ADD_TYPE(GSamplerCubeArray);
233 ADD_TYPE(GSamplerBuffer);
234 ADD_TYPE(GSampler2DMS);
235 ADD_TYPE(GSampler2DMSArray);
236
237 ADD_TYPE(Sampler1DShadow);
238 ADD_TYPE(Sampler2DShadow);
239 ADD_TYPE(SamplerCubeShadow);
240 ADD_TYPE(Sampler2DRectShadow);
241 ADD_TYPE(Sampler1DArrayShadow);
242 ADD_TYPE(Sampler2DArrayShadow);
243 ADD_TYPE(SamplerCubeArrayShadow);
244 ADD_TYPE(GSampler2DArrayShadow);
245 ADD_TYPE(GSamplerCubeArrayShadow);
Ethan Nicholasc9472af2017-10-10 16:30:21 -0400246 ADD_TYPE(FragmentProcessor);
Stephen Whiteff5d7a22019-07-26 17:42:06 -0400247 ADD_TYPE(Sampler);
248 ADD_TYPE(Texture2D);
ethannicholasb3058bd2016-07-01 08:22:01 -0700249
Brian Osman28590d52020-03-23 16:59:08 -0400250 StringFragment fpAliasName("shader");
Brian Osmaneac49832020-09-18 11:49:22 -0400251 fRootSymbolTable->addWithoutOwnership(fpAliasName, fContext->fFragmentProcessor_Type.get());
Brian Osman28590d52020-03-23 16:59:08 -0400252
Brian Osman3887a012020-09-30 13:22:27 -0400253 // sk_Caps is "builtin", but all references to it are resolved to Settings, so we don't need to
254 // treat it as builtin (ie, no need to clone it into the Program).
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700255 StringFragment skCapsName("sk_Caps");
Brian Osman3887a012020-09-30 13:22:27 -0400256 fRootSymbolTable->add(skCapsName,
257 std::make_unique<Variable>(/*offset=*/-1, Modifiers(), skCapsName,
258 fContext->fSkCaps_Type.get(),
259 /*builtin=*/false, Variable::kGlobal_Storage));
Ethan Nicholas3605ace2016-11-21 15:59:48 -0500260
Brian Osman00a8b5b2020-10-02 09:06:04 -0400261 fIRGenerator->fIntrinsics = nullptr;
262 std::vector<std::unique_ptr<ProgramElement>> gpuElements;
263 std::vector<std::unique_ptr<ProgramElement>> fragElements;
Brian Osmandd496172020-08-08 08:17:18 -0400264#if SKSL_STANDALONE
Brian Osmaneac49832020-09-18 11:49:22 -0400265 this->processIncludeFile(Program::kFragment_Kind, SKSL_GPU_INCLUDE, fRootSymbolTable,
Brian Osman00a8b5b2020-10-02 09:06:04 -0400266 &gpuElements, &fGpuSymbolTable);
Ethan Nicholasb33fa3f2020-08-06 13:00:19 -0400267 this->processIncludeFile(Program::kVertex_Kind, SKSL_VERT_INCLUDE, fGpuSymbolTable,
268 &fVertexInclude, &fVertexSymbolTable);
269 this->processIncludeFile(Program::kFragment_Kind, SKSL_FRAG_INCLUDE, fGpuSymbolTable,
Brian Osman00a8b5b2020-10-02 09:06:04 -0400270 &fragElements, &fFragmentSymbolTable);
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400271#else
272 {
Brian Osmaneac49832020-09-18 11:49:22 -0400273 Rehydrator rehydrator(fContext.get(), fRootSymbolTable, this, SKSL_INCLUDE_sksl_gpu,
274 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 Nicholasc18bb512020-07-28 14:46:53 -0400277 }
278 {
279 Rehydrator rehydrator(fContext.get(), fGpuSymbolTable, this, SKSL_INCLUDE_sksl_vert,
Brian Osmaneac49832020-09-18 11:49:22 -0400280 SKSL_INCLUDE_sksl_vert_LENGTH);
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400281 fVertexSymbolTable = rehydrator.symbolTable();
282 fVertexInclude = rehydrator.elements();
283 }
284 {
285 Rehydrator rehydrator(fContext.get(), fGpuSymbolTable, this, SKSL_INCLUDE_sksl_frag,
Brian Osmaneac49832020-09-18 11:49:22 -0400286 SKSL_INCLUDE_sksl_frag_LENGTH);
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400287 fFragmentSymbolTable = rehydrator.symbolTable();
Brian Osman00a8b5b2020-10-02 09:06:04 -0400288 fragElements = rehydrator.elements();
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400289 }
290#endif
John Stilesbc0c29e2020-09-28 13:13:40 -0400291 // Call counts are used to track dead-stripping and inlinability within the program being
292 // currently compiled, and always should start at zero for a new program. Zero out any call
293 // counts that were registered during the assembly of the intrinsics/include data. (If we
294 // actually use calls from inside the intrinsics, we will clone them into the program and they
295 // will get new call counts.)
Brian Osman00a8b5b2020-10-02 09:06:04 -0400296 reset_call_counts(&gpuElements);
John Stilesbc0c29e2020-09-28 13:13:40 -0400297 reset_call_counts(&fVertexInclude);
Brian Osman00a8b5b2020-10-02 09:06:04 -0400298 reset_call_counts(&fragElements);
John Stilesbc0c29e2020-09-28 13:13:40 -0400299
Brian Osman00a8b5b2020-10-02 09:06:04 -0400300 fGPUIntrinsics = std::make_unique<IRIntrinsicMap>(/*parent=*/nullptr);
301 grab_intrinsics(&gpuElements, fGPUIntrinsics.get());
302
303 fFragmentIntrinsics = std::make_unique<IRIntrinsicMap>(fGPUIntrinsics.get());
304 grab_intrinsics(&fragElements, fFragmentIntrinsics.get());
ethannicholasb3058bd2016-07-01 08:22:01 -0700305}
306
John Stiles656427a2020-08-27 15:26:26 -0400307Compiler::~Compiler() {}
ethannicholasb3058bd2016-07-01 08:22:01 -0700308
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400309void Compiler::loadGeometryIntrinsics() {
310 if (fGeometrySymbolTable) {
311 return;
312 }
Brian Osmandd496172020-08-08 08:17:18 -0400313 #if !SKSL_STANDALONE
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400314 {
315 Rehydrator rehydrator(fContext.get(), fGpuSymbolTable, this, SKSL_INCLUDE_sksl_geom,
316 SKSL_INCLUDE_sksl_geom_LENGTH);
317 fGeometrySymbolTable = rehydrator.symbolTable();
318 fGeometryInclude = rehydrator.elements();
319 }
320 #else
Ethan Nicholasb33fa3f2020-08-06 13:00:19 -0400321 this->processIncludeFile(Program::kGeometry_Kind, SKSL_GEOM_INCLUDE, fGpuSymbolTable,
322 &fGeometryInclude, &fGeometrySymbolTable);
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400323 #endif
324}
325
Brian Osman8e2ef022020-09-30 13:26:43 -0400326void Compiler::loadFPIntrinsics() {
327 if (fFPSymbolTable) {
328 return;
329 }
330 fFPIntrinsics = std::make_unique<IRIntrinsicMap>(fGPUIntrinsics.get());
331 std::vector<std::unique_ptr<ProgramElement>> fpElements;
332 #if !SKSL_STANDALONE
333 {
334 Rehydrator rehydrator(fContext.get(), fGpuSymbolTable, this, SKSL_INCLUDE_sksl_fp,
335 SKSL_INCLUDE_sksl_fp_LENGTH);
336 fFPSymbolTable = rehydrator.symbolTable();
337 fpElements = rehydrator.elements();
338 }
339 #else
340 this->processIncludeFile(Program::kFragmentProcessor_Kind, SKSL_FP_INCLUDE, fGpuSymbolTable,
341 &fpElements, &fFPSymbolTable);
342 #endif
343 grab_intrinsics(&fpElements, fFPIntrinsics.get());
Brian Osman8e2ef022020-09-30 13:26:43 -0400344}
345
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400346void Compiler::loadPipelineIntrinsics() {
347 if (fPipelineSymbolTable) {
348 return;
349 }
Brian Osman00a8b5b2020-10-02 09:06:04 -0400350 fPipelineIntrinsics = std::make_unique<IRIntrinsicMap>(fGPUIntrinsics.get());
Brian Osman8e2ef022020-09-30 13:26:43 -0400351 std::vector<std::unique_ptr<ProgramElement>> pipelineIntrinics;
Brian Osmandd496172020-08-08 08:17:18 -0400352 #if !SKSL_STANDALONE
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400353 {
354 Rehydrator rehydrator(fContext.get(), fGpuSymbolTable, this,
355 SKSL_INCLUDE_sksl_pipeline,
356 SKSL_INCLUDE_sksl_pipeline_LENGTH);
357 fPipelineSymbolTable = rehydrator.symbolTable();
Brian Osman8e2ef022020-09-30 13:26:43 -0400358 pipelineIntrinics = rehydrator.elements();
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400359 }
360 #else
361 this->processIncludeFile(Program::kPipelineStage_Kind, SKSL_PIPELINE_INCLUDE,
Brian Osman8e2ef022020-09-30 13:26:43 -0400362 fGpuSymbolTable, &pipelineIntrinics, &fPipelineSymbolTable);
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400363 #endif
Brian Osman8e2ef022020-09-30 13:26:43 -0400364 grab_intrinsics(&pipelineIntrinics, fPipelineIntrinsics.get());
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400365}
366
367void Compiler::loadInterpreterIntrinsics() {
368 if (fInterpreterSymbolTable) {
369 return;
370 }
Brian Osman00a8b5b2020-10-02 09:06:04 -0400371 fInterpreterIntrinsics = std::make_unique<IRIntrinsicMap>(/*parent=*/nullptr);
372 std::vector<std::unique_ptr<ProgramElement>> interpElements;
Brian Osmandd496172020-08-08 08:17:18 -0400373 #if !SKSL_STANDALONE
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400374 {
Brian Osmaneac49832020-09-18 11:49:22 -0400375 Rehydrator rehydrator(fContext.get(), fRootSymbolTable, this,
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400376 SKSL_INCLUDE_sksl_interp,
377 SKSL_INCLUDE_sksl_interp_LENGTH);
378 fInterpreterSymbolTable = rehydrator.symbolTable();
Brian Osman00a8b5b2020-10-02 09:06:04 -0400379 interpElements = rehydrator.elements();
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400380 }
381 #else
382 this->processIncludeFile(Program::kGeneric_Kind, SKSL_INTERP_INCLUDE,
Brian Osman00a8b5b2020-10-02 09:06:04 -0400383 fIRGenerator->fSymbolTable, &interpElements,
Ethan Nicholasb33fa3f2020-08-06 13:00:19 -0400384 &fInterpreterSymbolTable);
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400385 #endif
Brian Osman00a8b5b2020-10-02 09:06:04 -0400386 grab_intrinsics(&interpElements, fInterpreterIntrinsics.get());
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400387}
388
Ethan Nicholasb33fa3f2020-08-06 13:00:19 -0400389void Compiler::processIncludeFile(Program::Kind kind, const char* path,
Ethan Nicholas8da1e652019-05-24 11:01:59 -0400390 std::shared_ptr<SymbolTable> base,
391 std::vector<std::unique_ptr<ProgramElement>>* outElements,
392 std::shared_ptr<SymbolTable>* outSymbolTable) {
Ethan Nicholasb33fa3f2020-08-06 13:00:19 -0400393 std::ifstream in(path);
Brian Osmane498b3c2020-09-23 14:42:11 -0400394 std::unique_ptr<String> text = std::make_unique<String>(std::istreambuf_iterator<char>(in),
395 std::istreambuf_iterator<char>());
Ethan Nicholasb33fa3f2020-08-06 13:00:19 -0400396 if (in.rdstate()) {
397 printf("error reading %s\n", path);
398 abort();
399 }
Brian Osmane498b3c2020-09-23 14:42:11 -0400400 const String* source = fRootSymbolTable->takeOwnershipOfString(std::move(text));
Ethan Nicholasb33fa3f2020-08-06 13:00:19 -0400401 fSource = source;
Ethan Nicholas8da1e652019-05-24 11:01:59 -0400402 Program::Settings settings;
Ethan Nicholasa11035b2019-11-26 16:27:47 -0500403#if !defined(SKSL_STANDALONE) & SK_SUPPORT_GPU
404 GrContextOptions opts;
405 GrShaderCaps caps(opts);
406 settings.fCaps = &caps;
407#endif
John Stiles881a10c2020-09-19 10:13:24 -0400408 SkASSERT(fIRGenerator->fCanInline);
409 fIRGenerator->fCanInline = false;
Brian Osmane498b3c2020-09-23 14:42:11 -0400410 fIRGenerator->start(&settings, base ? base : fRootSymbolTable, nullptr, true);
Ethan Nicholasb33fa3f2020-08-06 13:00:19 -0400411 fIRGenerator->convertProgram(kind, source->c_str(), source->length(), outElements);
John Stiles881a10c2020-09-19 10:13:24 -0400412 fIRGenerator->fCanInline = true;
Ethan Nicholas8da1e652019-05-24 11:01:59 -0400413 if (this->fErrorCount) {
414 printf("Unexpected errors: %s\n", this->fErrorText.c_str());
415 }
416 SkASSERT(!fErrorCount);
Ethan Nicholas8da1e652019-05-24 11:01:59 -0400417 *outSymbolTable = fIRGenerator->fSymbolTable;
Ethan Nicholasa11035b2019-11-26 16:27:47 -0500418#ifdef SK_DEBUG
419 fSource = nullptr;
420#endif
Brian Osmane498b3c2020-09-23 14:42:11 -0400421 fIRGenerator->finish();
Ethan Nicholas8da1e652019-05-24 11:01:59 -0400422}
423
ethannicholas22f939e2016-10-13 13:25:34 -0700424// add the definition created by assigning to the lvalue to the definition set
Ethan Nicholas86a43402017-01-19 13:32:00 -0500425void Compiler::addDefinition(const Expression* lvalue, std::unique_ptr<Expression>* expr,
426 DefinitionMap* definitions) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400427 switch (lvalue->kind()) {
428 case Expression::Kind::kVariableReference: {
Brian Osman79457ef2020-09-24 15:01:27 -0400429 const Variable& var = *lvalue->as<VariableReference>().fVariable;
ethannicholas22f939e2016-10-13 13:25:34 -0700430 if (var.fStorage == Variable::kLocal_Storage) {
431 (*definitions)[&var] = expr;
432 }
433 break;
434 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400435 case Expression::Kind::kSwizzle:
ethannicholas22f939e2016-10-13 13:25:34 -0700436 // We consider the variable written to as long as at least some of its components have
437 // been written to. This will lead to some false negatives (we won't catch it if you
438 // write to foo.x and then read foo.y), but being stricter could lead to false positives
Mike Klein6ad99092016-10-26 10:35:22 -0400439 // (we write to foo.x, and then pass foo to a function which happens to only read foo.x,
440 // 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 -0700441 // more complicated whole-program analysis. This is probably good enough.
John Stilesa5a97b42020-08-18 11:19:07 -0400442 this->addDefinition(lvalue->as<Swizzle>().fBase.get(),
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400443 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
ethannicholas22f939e2016-10-13 13:25:34 -0700444 definitions);
445 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400446 case Expression::Kind::kIndex:
ethannicholas22f939e2016-10-13 13:25:34 -0700447 // see comments in Swizzle
John Stilesa5a97b42020-08-18 11:19:07 -0400448 this->addDefinition(lvalue->as<IndexExpression>().fBase.get(),
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400449 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
ethannicholas22f939e2016-10-13 13:25:34 -0700450 definitions);
451 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400452 case Expression::Kind::kFieldAccess:
ethannicholas22f939e2016-10-13 13:25:34 -0700453 // see comments in Swizzle
John Stilesa5a97b42020-08-18 11:19:07 -0400454 this->addDefinition(lvalue->as<FieldAccess>().fBase.get(),
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400455 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
ethannicholas22f939e2016-10-13 13:25:34 -0700456 definitions);
457 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400458 case Expression::Kind::kTernary:
Ethan Nicholasa583b812018-01-18 13:32:11 -0500459 // To simplify analysis, we just pretend that we write to both sides of the ternary.
460 // This allows for false positives (meaning we fail to detect that a variable might not
461 // have been assigned), but is preferable to false negatives.
John Stilesa5a97b42020-08-18 11:19:07 -0400462 this->addDefinition(lvalue->as<TernaryExpression>().fIfTrue.get(),
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400463 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
Ethan Nicholasa583b812018-01-18 13:32:11 -0500464 definitions);
John Stilesa5a97b42020-08-18 11:19:07 -0400465 this->addDefinition(lvalue->as<TernaryExpression>().fIfFalse.get(),
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400466 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
Ethan Nicholasa583b812018-01-18 13:32:11 -0500467 definitions);
468 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400469 case Expression::Kind::kExternalValue:
Ethan Nicholas91164d12019-05-15 15:29:54 -0400470 break;
ethannicholas22f939e2016-10-13 13:25:34 -0700471 default:
472 // not an lvalue, can't happen
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400473 SkASSERT(false);
ethannicholas22f939e2016-10-13 13:25:34 -0700474 }
475}
476
477// add local variables defined by this node to the set
Mike Klein6ad99092016-10-26 10:35:22 -0400478void Compiler::addDefinitions(const BasicBlock::Node& node,
Ethan Nicholas86a43402017-01-19 13:32:00 -0500479 DefinitionMap* definitions) {
John Stiles70025e52020-09-28 16:08:58 -0400480 if (node.isExpression()) {
481 Expression* expr = node.expression()->get();
482 switch (expr->kind()) {
483 case Expression::Kind::kBinary: {
484 BinaryExpression* b = &expr->as<BinaryExpression>();
485 if (b->getOperator() == Token::Kind::TK_EQ) {
486 this->addDefinition(&b->left(), &b->rightPointer(), definitions);
487 } else if (Compiler::IsAssignment(b->getOperator())) {
488 this->addDefinition(
489 &b->left(),
490 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
491 definitions);
Ethan Nicholas86a43402017-01-19 13:32:00 -0500492
ethannicholas22f939e2016-10-13 13:25:34 -0700493 }
John Stiles70025e52020-09-28 16:08:58 -0400494 break;
ethannicholas22f939e2016-10-13 13:25:34 -0700495 }
John Stiles70025e52020-09-28 16:08:58 -0400496 case Expression::Kind::kFunctionCall: {
497 const FunctionCall& c = expr->as<FunctionCall>();
498 for (size_t i = 0; i < c.fFunction.fParameters.size(); ++i) {
499 if (c.fFunction.fParameters[i]->fModifiers.fFlags & Modifiers::kOut_Flag) {
500 this->addDefinition(
501 c.fArguments[i].get(),
502 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
503 definitions);
504 }
505 }
506 break;
507 }
508 case Expression::Kind::kPrefix: {
509 const PrefixExpression* p = &expr->as<PrefixExpression>();
510 if (p->fOperator == Token::Kind::TK_MINUSMINUS ||
511 p->fOperator == Token::Kind::TK_PLUSPLUS) {
512 this->addDefinition(
513 p->fOperand.get(),
514 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
515 definitions);
516 }
517 break;
518 }
519 case Expression::Kind::kPostfix: {
520 const PostfixExpression* p = &expr->as<PostfixExpression>();
521 if (p->fOperator == Token::Kind::TK_MINUSMINUS ||
522 p->fOperator == Token::Kind::TK_PLUSPLUS) {
523 this->addDefinition(
524 p->fOperand.get(),
525 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
526 definitions);
527 }
528 break;
529 }
530 case Expression::Kind::kVariableReference: {
531 const VariableReference* v = &expr->as<VariableReference>();
532 if (v->fRefKind != VariableReference::kRead_RefKind) {
533 this->addDefinition(
534 v,
535 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
536 definitions);
537 }
538 break;
539 }
540 default:
541 break;
ethannicholas22f939e2016-10-13 13:25:34 -0700542 }
John Stiles70025e52020-09-28 16:08:58 -0400543 } else if (node.isStatement()) {
544 Statement* stmt = node.statement()->get();
545 if (stmt->is<VarDeclaration>()) {
546 VarDeclaration& vd = stmt->as<VarDeclaration>();
547 if (vd.fValue) {
548 (*definitions)[vd.fVar] = &vd.fValue;
ethannicholas22f939e2016-10-13 13:25:34 -0700549 }
ethannicholas22f939e2016-10-13 13:25:34 -0700550 }
551 }
552}
553
John Stilese6150002020-10-05 12:03:53 -0400554void Compiler::scanCFG(CFG* cfg, BlockId blockId, SkBitSet* processedSet) {
ethannicholas22f939e2016-10-13 13:25:34 -0700555 BasicBlock& block = cfg->fBlocks[blockId];
556
557 // compute definitions after this block
Ethan Nicholas86a43402017-01-19 13:32:00 -0500558 DefinitionMap after = block.fBefore;
ethannicholas22f939e2016-10-13 13:25:34 -0700559 for (const BasicBlock::Node& n : block.fNodes) {
560 this->addDefinitions(n, &after);
561 }
562
563 // propagate definitions to exits
564 for (BlockId exitId : block.fExits) {
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400565 if (exitId == blockId) {
566 continue;
567 }
ethannicholas22f939e2016-10-13 13:25:34 -0700568 BasicBlock& exit = cfg->fBlocks[exitId];
569 for (const auto& pair : after) {
Ethan Nicholas86a43402017-01-19 13:32:00 -0500570 std::unique_ptr<Expression>* e1 = pair.second;
571 auto found = exit.fBefore.find(pair.first);
572 if (found == exit.fBefore.end()) {
John Stilese6150002020-10-05 12:03:53 -0400573 // exit has no definition for it, just copy it and reprocess exit block
574 processedSet->reset(exitId);
ethannicholas22f939e2016-10-13 13:25:34 -0700575 exit.fBefore[pair.first] = e1;
576 } else {
Ethan Nicholas86a43402017-01-19 13:32:00 -0500577 // exit has a (possibly different) value already defined
578 std::unique_ptr<Expression>* e2 = exit.fBefore[pair.first];
ethannicholas22f939e2016-10-13 13:25:34 -0700579 if (e1 != e2) {
John Stilese6150002020-10-05 12:03:53 -0400580 // definition has changed, merge and reprocess the exit block
581 processedSet->reset(exitId);
Ethan Nicholasaf197692017-02-27 13:26:45 -0500582 if (e1 && e2) {
583 exit.fBefore[pair.first] =
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400584 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression;
Ethan Nicholasaf197692017-02-27 13:26:45 -0500585 } else {
586 exit.fBefore[pair.first] = nullptr;
587 }
ethannicholas22f939e2016-10-13 13:25:34 -0700588 }
589 }
590 }
591 }
592}
593
594// returns a map which maps all local variables in the function to null, indicating that their value
595// is initially unknown
Ethan Nicholas86a43402017-01-19 13:32:00 -0500596static DefinitionMap compute_start_state(const CFG& cfg) {
597 DefinitionMap result;
Mike Klein6ad99092016-10-26 10:35:22 -0400598 for (const auto& block : cfg.fBlocks) {
599 for (const auto& node : block.fNodes) {
John Stiles70025e52020-09-28 16:08:58 -0400600 if (node.isStatement()) {
Ethan Nicholascb670962017-04-20 19:31:52 -0400601 const Statement* s = node.statement()->get();
Brian Osman79457ef2020-09-24 15:01:27 -0400602 if (s->is<VarDeclarationsStatement>()) {
John Stilesa5a97b42020-08-18 11:19:07 -0400603 const VarDeclarationsStatement* vd = &s->as<VarDeclarationsStatement>();
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000604 for (const auto& decl : vd->fDeclaration->fVars) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400605 if (decl->kind() == Statement::Kind::kVarDeclaration) {
John Stilesa5a97b42020-08-18 11:19:07 -0400606 result[decl->as<VarDeclaration>().fVar] = nullptr;
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000607 }
Mike Klein6ad99092016-10-26 10:35:22 -0400608 }
ethannicholas22f939e2016-10-13 13:25:34 -0700609 }
610 }
611 }
612 }
613 return result;
614}
615
Ethan Nicholascb670962017-04-20 19:31:52 -0400616/**
617 * Returns true if assigning to this lvalue has no effect.
618 */
619static bool is_dead(const Expression& lvalue) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400620 switch (lvalue.kind()) {
621 case Expression::Kind::kVariableReference:
Brian Osman79457ef2020-09-24 15:01:27 -0400622 return lvalue.as<VariableReference>().fVariable->dead();
Ethan Nicholase6592142020-09-08 10:22:09 -0400623 case Expression::Kind::kSwizzle:
John Stilesa5a97b42020-08-18 11:19:07 -0400624 return is_dead(*lvalue.as<Swizzle>().fBase);
Ethan Nicholase6592142020-09-08 10:22:09 -0400625 case Expression::Kind::kFieldAccess:
John Stilesa5a97b42020-08-18 11:19:07 -0400626 return is_dead(*lvalue.as<FieldAccess>().fBase);
Ethan Nicholase6592142020-09-08 10:22:09 -0400627 case Expression::Kind::kIndex: {
John Stilesa5a97b42020-08-18 11:19:07 -0400628 const IndexExpression& idx = lvalue.as<IndexExpression>();
Ethan Nicholas2a099da2020-01-02 14:40:54 -0500629 return is_dead(*idx.fBase) &&
630 !idx.fIndex->hasProperty(Expression::Property::kSideEffects);
Ethan Nicholascb670962017-04-20 19:31:52 -0400631 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400632 case Expression::Kind::kTernary: {
John Stilesa5a97b42020-08-18 11:19:07 -0400633 const TernaryExpression& t = lvalue.as<TernaryExpression>();
Ethan Nicholasa583b812018-01-18 13:32:11 -0500634 return !t.fTest->hasSideEffects() && is_dead(*t.fIfTrue) && is_dead(*t.fIfFalse);
635 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400636 case Expression::Kind::kExternalValue:
Ethan Nicholas91164d12019-05-15 15:29:54 -0400637 return false;
Ethan Nicholascb670962017-04-20 19:31:52 -0400638 default:
Ethan Nicholas2a099da2020-01-02 14:40:54 -0500639#ifdef SK_DEBUG
Ethan Nicholascb670962017-04-20 19:31:52 -0400640 ABORT("invalid lvalue: %s\n", lvalue.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -0500641#endif
642 return false;
Ethan Nicholascb670962017-04-20 19:31:52 -0400643 }
644}
ethannicholas22f939e2016-10-13 13:25:34 -0700645
Ethan Nicholascb670962017-04-20 19:31:52 -0400646/**
647 * Returns true if this is an assignment which can be collapsed down to just the right hand side due
648 * to a dead target and lack of side effects on the left hand side.
649 */
650static bool dead_assignment(const BinaryExpression& b) {
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400651 if (!Compiler::IsAssignment(b.getOperator())) {
Ethan Nicholascb670962017-04-20 19:31:52 -0400652 return false;
653 }
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400654 return is_dead(b.left());
Ethan Nicholascb670962017-04-20 19:31:52 -0400655}
656
657void Compiler::computeDataFlow(CFG* cfg) {
658 cfg->fBlocks[cfg->fStart].fBefore = compute_start_state(*cfg);
John Stilese6150002020-10-05 12:03:53 -0400659
660 // We set bits in the "processed" set after a block has been scanned.
661 SkBitSet processedSet(cfg->fBlocks.size());
662 while (SkBitSet::OptionalIndex blockId = processedSet.findFirstUnset()) {
663 processedSet.set(*blockId);
664 this->scanCFG(cfg, *blockId, &processedSet);
ethannicholas22f939e2016-10-13 13:25:34 -0700665 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400666}
667
668/**
669 * Attempts to replace the expression pointed to by iter with a new one (in both the CFG and the
670 * IR). If the expression can be cleanly removed, returns true and updates the iterator to point to
671 * the newly-inserted element. Otherwise updates only the IR and returns false (and the CFG will
672 * need to be regenerated).
673 */
John Stilesafbf8992020-08-18 10:08:21 -0400674static bool try_replace_expression(BasicBlock* b,
675 std::vector<BasicBlock::Node>::iterator* iter,
676 std::unique_ptr<Expression>* newExpression) {
Ethan Nicholascb670962017-04-20 19:31:52 -0400677 std::unique_ptr<Expression>* target = (*iter)->expression();
678 if (!b->tryRemoveExpression(iter)) {
679 *target = std::move(*newExpression);
680 return false;
681 }
682 *target = std::move(*newExpression);
683 return b->tryInsertExpression(iter, target);
684}
685
686/**
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400687 * Returns true if the expression is a constant numeric literal with the specified value, or a
688 * constant vector with all elements equal to the specified value.
Ethan Nicholascb670962017-04-20 19:31:52 -0400689 */
Ethan Nicholasa3f22f12020-10-01 12:13:17 -0400690template <typename T = SKSL_FLOAT>
John Stiles9d944232020-08-19 09:56:49 -0400691static bool is_constant(const Expression& expr, T value) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400692 switch (expr.kind()) {
693 case Expression::Kind::kIntLiteral:
Ethan Nicholase96cdd12020-09-28 16:27:18 -0400694 return expr.as<IntLiteral>().value() == value;
John Stiles9d944232020-08-19 09:56:49 -0400695
Ethan Nicholase6592142020-09-08 10:22:09 -0400696 case Expression::Kind::kFloatLiteral:
Ethan Nicholasa3f22f12020-10-01 12:13:17 -0400697 return expr.as<FloatLiteral>().value() == value;
John Stiles9d944232020-08-19 09:56:49 -0400698
Ethan Nicholase6592142020-09-08 10:22:09 -0400699 case Expression::Kind::kConstructor: {
John Stiles9d944232020-08-19 09:56:49 -0400700 const Constructor& constructor = expr.as<Constructor>();
701 if (constructor.isCompileTimeConstant()) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400702 const Type& constructorType = constructor.type();
703 bool isFloat = constructorType.columns() > 1
704 ? constructorType.componentType().isFloat()
705 : constructorType.isFloat();
706 switch (constructorType.typeKind()) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400707 case Type::TypeKind::kVector:
Ethan Nicholas30d30222020-09-11 12:27:26 -0400708 for (int i = 0; i < constructorType.columns(); ++i) {
John Stiles9d944232020-08-19 09:56:49 -0400709 if (isFloat) {
710 if (constructor.getFVecComponent(i) != value) {
711 return false;
712 }
713 } else {
714 if (constructor.getIVecComponent(i) != value) {
715 return false;
716 }
717 }
Ethan Nicholasd188c182019-06-10 15:55:38 -0400718 }
John Stiles9d944232020-08-19 09:56:49 -0400719 return true;
720
Ethan Nicholase6592142020-09-08 10:22:09 -0400721 case Type::TypeKind::kScalar:
Ethan Nicholasf70f0442020-09-29 12:41:35 -0400722 SkASSERT(constructor.arguments().size() == 1);
723 return is_constant<T>(*constructor.arguments()[0], value);
John Stiles9d944232020-08-19 09:56:49 -0400724
725 default:
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400726 return false;
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400727 }
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400728 }
729 return false;
730 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400731 default:
732 return false;
733 }
734}
735
736/**
737 * Collapses the binary expression pointed to by iter down to just the right side (in both the IR
738 * and CFG structures).
739 */
John Stilesafbf8992020-08-18 10:08:21 -0400740static void delete_left(BasicBlock* b,
741 std::vector<BasicBlock::Node>::iterator* iter,
742 bool* outUpdated,
743 bool* outNeedsRescan) {
Ethan Nicholascb670962017-04-20 19:31:52 -0400744 *outUpdated = true;
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400745 std::unique_ptr<Expression>* target = (*iter)->expression();
John Stilesa5a97b42020-08-18 11:19:07 -0400746 BinaryExpression& bin = (*target)->as<BinaryExpression>();
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400747 Expression& left = bin.left();
748 std::unique_ptr<Expression>& rightPointer = bin.rightPointer();
749 SkASSERT(!left.hasSideEffects());
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400750 bool result;
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400751 if (bin.getOperator() == Token::Kind::TK_EQ) {
752 result = b->tryRemoveLValueBefore(iter, &left);
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400753 } else {
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400754 result = b->tryRemoveExpressionBefore(iter, &left);
Ethan Nicholascb670962017-04-20 19:31:52 -0400755 }
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400756 *target = std::move(rightPointer);
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400757 if (!result) {
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400758 *outNeedsRescan = true;
759 return;
760 }
761 if (*iter == b->fNodes.begin()) {
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400762 *outNeedsRescan = true;
763 return;
764 }
765 --(*iter);
John Stiles70025e52020-09-28 16:08:58 -0400766 if (!(*iter)->isExpression() || (*iter)->expression() != &rightPointer) {
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400767 *outNeedsRescan = true;
768 return;
769 }
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400770 *iter = b->fNodes.erase(*iter);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400771 SkASSERT((*iter)->expression() == target);
Ethan Nicholascb670962017-04-20 19:31:52 -0400772}
773
774/**
775 * Collapses the binary expression pointed to by iter down to just the left side (in both the IR and
776 * CFG structures).
777 */
John Stilesafbf8992020-08-18 10:08:21 -0400778static void delete_right(BasicBlock* b,
779 std::vector<BasicBlock::Node>::iterator* iter,
780 bool* outUpdated,
781 bool* outNeedsRescan) {
Ethan Nicholascb670962017-04-20 19:31:52 -0400782 *outUpdated = true;
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400783 std::unique_ptr<Expression>* target = (*iter)->expression();
John Stilesa5a97b42020-08-18 11:19:07 -0400784 BinaryExpression& bin = (*target)->as<BinaryExpression>();
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400785 std::unique_ptr<Expression>& leftPointer = bin.leftPointer();
786 Expression& right = bin.right();
787 SkASSERT(!right.hasSideEffects());
788 if (!b->tryRemoveExpressionBefore(iter, &right)) {
789 *target = std::move(leftPointer);
Ethan Nicholascb670962017-04-20 19:31:52 -0400790 *outNeedsRescan = true;
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400791 return;
Ethan Nicholascb670962017-04-20 19:31:52 -0400792 }
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400793 *target = std::move(leftPointer);
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400794 if (*iter == b->fNodes.begin()) {
795 *outNeedsRescan = true;
796 return;
797 }
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400798 --(*iter);
John Stiles70025e52020-09-28 16:08:58 -0400799 if ((!(*iter)->isExpression() || (*iter)->expression() != &leftPointer)) {
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400800 *outNeedsRescan = true;
801 return;
802 }
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400803 *iter = b->fNodes.erase(*iter);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400804 SkASSERT((*iter)->expression() == target);
Ethan Nicholascb670962017-04-20 19:31:52 -0400805}
806
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400807/**
808 * Constructs the specified type using a single argument.
809 */
Ethan Nicholas30d30222020-09-11 12:27:26 -0400810static std::unique_ptr<Expression> construct(const Type* type, std::unique_ptr<Expression> v) {
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400811 std::vector<std::unique_ptr<Expression>> args;
812 args.push_back(std::move(v));
Ethan Nicholase6592142020-09-08 10:22:09 -0400813 std::unique_ptr<Expression> result = std::make_unique<Constructor>(-1, type, std::move(args));
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400814 return result;
815}
816
817/**
818 * Used in the implementations of vectorize_left and vectorize_right. Given a vector type and an
819 * expression x, deletes the expression pointed to by iter and replaces it with <type>(x).
820 */
821static void vectorize(BasicBlock* b,
822 std::vector<BasicBlock::Node>::iterator* iter,
823 const Type& type,
824 std::unique_ptr<Expression>* otherExpression,
825 bool* outUpdated,
826 bool* outNeedsRescan) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400827 SkASSERT((*(*iter)->expression())->kind() == Expression::Kind::kBinary);
828 SkASSERT(type.typeKind() == Type::TypeKind::kVector);
Ethan Nicholas30d30222020-09-11 12:27:26 -0400829 SkASSERT((*otherExpression)->type().typeKind() == Type::TypeKind::kScalar);
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400830 *outUpdated = true;
831 std::unique_ptr<Expression>* target = (*iter)->expression();
832 if (!b->tryRemoveExpression(iter)) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400833 *target = construct(&type, std::move(*otherExpression));
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400834 *outNeedsRescan = true;
835 } else {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400836 *target = construct(&type, std::move(*otherExpression));
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400837 if (!b->tryInsertExpression(iter, target)) {
838 *outNeedsRescan = true;
839 }
840 }
841}
842
843/**
844 * Given a binary expression of the form x <op> vec<n>(y), deletes the right side and vectorizes the
845 * left to yield vec<n>(x).
846 */
847static void vectorize_left(BasicBlock* b,
848 std::vector<BasicBlock::Node>::iterator* iter,
849 bool* outUpdated,
850 bool* outNeedsRescan) {
John Stilesa5a97b42020-08-18 11:19:07 -0400851 BinaryExpression& bin = (*(*iter)->expression())->as<BinaryExpression>();
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400852 vectorize(b, iter, bin.right().type(), &bin.leftPointer(), outUpdated, outNeedsRescan);
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400853}
854
855/**
856 * Given a binary expression of the form vec<n>(x) <op> y, deletes the left side and vectorizes the
857 * right to yield vec<n>(y).
858 */
859static void vectorize_right(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.left().type(), &bin.rightPointer(), outUpdated, outNeedsRescan);
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400865}
866
867// Mark that an expression which we were writing to is no longer being written to
John Stilesa5a97b42020-08-18 11:19:07 -0400868static void clear_write(Expression& expr) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400869 switch (expr.kind()) {
870 case Expression::Kind::kVariableReference: {
John Stilesa5a97b42020-08-18 11:19:07 -0400871 expr.as<VariableReference>().setRefKind(VariableReference::kRead_RefKind);
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400872 break;
873 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400874 case Expression::Kind::kFieldAccess:
John Stilesa5a97b42020-08-18 11:19:07 -0400875 clear_write(*expr.as<FieldAccess>().fBase);
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400876 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400877 case Expression::Kind::kSwizzle:
John Stilesa5a97b42020-08-18 11:19:07 -0400878 clear_write(*expr.as<Swizzle>().fBase);
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400879 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400880 case Expression::Kind::kIndex:
John Stilesa5a97b42020-08-18 11:19:07 -0400881 clear_write(*expr.as<IndexExpression>().fBase);
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400882 break;
883 default:
884 ABORT("shouldn't be writing to this kind of expression\n");
885 break;
886 }
887}
888
Ethan Nicholascb670962017-04-20 19:31:52 -0400889void Compiler::simplifyExpression(DefinitionMap& definitions,
890 BasicBlock& b,
891 std::vector<BasicBlock::Node>::iterator* iter,
892 std::unordered_set<const Variable*>* undefinedVariables,
893 bool* outUpdated,
894 bool* outNeedsRescan) {
895 Expression* expr = (*iter)->expression()->get();
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400896 SkASSERT(expr);
Ethan Nicholascb670962017-04-20 19:31:52 -0400897 if ((*iter)->fConstantPropagation) {
898 std::unique_ptr<Expression> optimized = expr->constantPropagate(*fIRGenerator, definitions);
899 if (optimized) {
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400900 *outUpdated = true;
Ethan Nicholas30d30222020-09-11 12:27:26 -0400901 optimized = fIRGenerator->coerce(std::move(optimized), expr->type());
Ethan Nicholas1d881522020-09-11 09:32:54 -0400902 SkASSERT(optimized);
Ethan Nicholascb670962017-04-20 19:31:52 -0400903 if (!try_replace_expression(&b, iter, &optimized)) {
904 *outNeedsRescan = true;
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400905 return;
Ethan Nicholascb670962017-04-20 19:31:52 -0400906 }
John Stiles70025e52020-09-28 16:08:58 -0400907 SkASSERT((*iter)->isExpression());
Ethan Nicholascb670962017-04-20 19:31:52 -0400908 expr = (*iter)->expression()->get();
Ethan Nicholascb670962017-04-20 19:31:52 -0400909 }
910 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400911 switch (expr->kind()) {
912 case Expression::Kind::kVariableReference: {
John Stilesa5a97b42020-08-18 11:19:07 -0400913 const VariableReference& ref = expr->as<VariableReference>();
Brian Osman79457ef2020-09-24 15:01:27 -0400914 const Variable* var = ref.fVariable;
Ethan Nicholas8f7e28f2018-03-26 14:24:27 -0400915 if (ref.refKind() != VariableReference::kWrite_RefKind &&
916 ref.refKind() != VariableReference::kPointer_RefKind &&
Brian Osman79457ef2020-09-24 15:01:27 -0400917 var->fStorage == Variable::kLocal_Storage && !definitions[var] &&
918 (*undefinedVariables).find(var) == (*undefinedVariables).end()) {
919 (*undefinedVariables).insert(var);
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000920 this->error(expr->fOffset,
Brian Osman58384ad2020-10-02 22:15:22 +0000921 "'" + var->fName + "' has not been assigned");
Ethan Nicholascb670962017-04-20 19:31:52 -0400922 }
923 break;
924 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400925 case Expression::Kind::kTernary: {
John Stiles403a3632020-08-20 12:11:48 -0400926 TernaryExpression* t = &expr->as<TernaryExpression>();
Ethan Nicholase6592142020-09-08 10:22:09 -0400927 if (t->fTest->kind() == Expression::Kind::kBoolLiteral) {
Ethan Nicholascb670962017-04-20 19:31:52 -0400928 // ternary has a constant test, replace it with either the true or
929 // false branch
Ethan Nicholas59d660c2020-09-28 09:18:15 -0400930 if (t->fTest->as<BoolLiteral>().value()) {
Ethan Nicholascb670962017-04-20 19:31:52 -0400931 (*iter)->setExpression(std::move(t->fIfTrue));
932 } else {
933 (*iter)->setExpression(std::move(t->fIfFalse));
934 }
935 *outUpdated = true;
936 *outNeedsRescan = true;
937 }
938 break;
939 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400940 case Expression::Kind::kBinary: {
John Stiles403a3632020-08-20 12:11:48 -0400941 BinaryExpression* bin = &expr->as<BinaryExpression>();
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400942 if (dead_assignment(*bin)) {
943 delete_left(&b, iter, outUpdated, outNeedsRescan);
944 break;
945 }
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400946 Expression& left = bin->left();
947 Expression& right = bin->right();
948 const Type& leftType = left.type();
949 const Type& rightType = right.type();
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400950 // collapse useless expressions like x * 1 or x + 0
Ethan Nicholas30d30222020-09-11 12:27:26 -0400951 if (((leftType.typeKind() != Type::TypeKind::kScalar) &&
952 (leftType.typeKind() != Type::TypeKind::kVector)) ||
953 ((rightType.typeKind() != Type::TypeKind::kScalar) &&
954 (rightType.typeKind() != Type::TypeKind::kVector))) {
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400955 break;
956 }
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400957 switch (bin->getOperator()) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400958 case Token::Kind::TK_STAR:
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400959 if (is_constant(left, 1)) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400960 if (leftType.typeKind() == Type::TypeKind::kVector &&
961 rightType.typeKind() == Type::TypeKind::kScalar) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400962 // float4(1) * x -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400963 vectorize_right(&b, iter, outUpdated, outNeedsRescan);
964 } else {
965 // 1 * x -> x
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400966 // 1 * float4(x) -> float4(x)
967 // float4(1) * float4(x) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400968 delete_left(&b, iter, outUpdated, outNeedsRescan);
969 }
970 }
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400971 else if (is_constant(left, 0)) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400972 if (leftType.typeKind() == Type::TypeKind::kScalar &&
973 rightType.typeKind() == Type::TypeKind::kVector &&
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400974 !right.hasSideEffects()) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400975 // 0 * float4(x) -> float4(0)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400976 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
977 } else {
978 // 0 * x -> 0
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400979 // float4(0) * x -> float4(0)
980 // float4(0) * float4(x) -> float4(0)
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400981 if (!right.hasSideEffects()) {
Ethan Nicholas51493ee2017-12-11 12:34:33 -0500982 delete_right(&b, iter, outUpdated, outNeedsRescan);
983 }
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400984 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400985 }
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400986 else if (is_constant(right, 1)) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400987 if (leftType.typeKind() == Type::TypeKind::kScalar &&
988 rightType.typeKind() == Type::TypeKind::kVector) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400989 // x * float4(1) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400990 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
991 } else {
992 // x * 1 -> x
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400993 // float4(x) * 1 -> float4(x)
994 // float4(x) * float4(1) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400995 delete_right(&b, iter, outUpdated, outNeedsRescan);
996 }
997 }
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400998 else if (is_constant(right, 0)) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400999 if (leftType.typeKind() == Type::TypeKind::kVector &&
1000 rightType.typeKind() == Type::TypeKind::kScalar &&
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001001 !left.hasSideEffects()) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -04001002 // float4(x) * 0 -> float4(0)
Ethan Nicholasfe53e582017-04-27 16:24:51 -04001003 vectorize_right(&b, iter, outUpdated, outNeedsRescan);
1004 } else {
1005 // x * 0 -> 0
Ethan Nicholas5af9ea32017-07-28 15:19:46 -04001006 // x * float4(0) -> float4(0)
1007 // float4(x) * float4(0) -> float4(0)
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001008 if (!left.hasSideEffects()) {
Ethan Nicholas51493ee2017-12-11 12:34:33 -05001009 delete_left(&b, iter, outUpdated, outNeedsRescan);
1010 }
Ethan Nicholasfe53e582017-04-27 16:24:51 -04001011 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001012 }
1013 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001014 case Token::Kind::TK_PLUS:
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001015 if (is_constant(left, 0)) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04001016 if (leftType.typeKind() == Type::TypeKind::kVector &&
1017 rightType.typeKind() == Type::TypeKind::kScalar) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -04001018 // float4(0) + x -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -04001019 vectorize_right(&b, iter, outUpdated, outNeedsRescan);
1020 } else {
1021 // 0 + x -> x
Ethan Nicholas5af9ea32017-07-28 15:19:46 -04001022 // 0 + float4(x) -> float4(x)
1023 // float4(0) + float4(x) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -04001024 delete_left(&b, iter, outUpdated, outNeedsRescan);
1025 }
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001026 } else if (is_constant(right, 0)) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04001027 if (leftType.typeKind() == Type::TypeKind::kScalar &&
1028 rightType.typeKind() == Type::TypeKind::kVector) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -04001029 // x + float4(0) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -04001030 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
1031 } else {
1032 // x + 0 -> x
Ethan Nicholas5af9ea32017-07-28 15:19:46 -04001033 // float4(x) + 0 -> float4(x)
1034 // float4(x) + float4(0) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -04001035 delete_right(&b, iter, outUpdated, outNeedsRescan);
1036 }
Ethan Nicholas56e42712017-04-21 10:23:37 -04001037 }
1038 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001039 case Token::Kind::TK_MINUS:
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001040 if (is_constant(right, 0)) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04001041 if (leftType.typeKind() == Type::TypeKind::kScalar &&
1042 rightType.typeKind() == Type::TypeKind::kVector) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -04001043 // x - float4(0) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -04001044 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
1045 } else {
1046 // x - 0 -> x
Ethan Nicholas5af9ea32017-07-28 15:19:46 -04001047 // float4(x) - 0 -> float4(x)
1048 // float4(x) - float4(0) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -04001049 delete_right(&b, iter, outUpdated, outNeedsRescan);
1050 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001051 }
1052 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001053 case Token::Kind::TK_SLASH:
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001054 if (is_constant(right, 1)) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04001055 if (leftType.typeKind() == Type::TypeKind::kScalar &&
1056 rightType.typeKind() == Type::TypeKind::kVector) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -04001057 // x / float4(1) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -04001058 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
1059 } else {
1060 // x / 1 -> x
Ethan Nicholas5af9ea32017-07-28 15:19:46 -04001061 // float4(x) / 1 -> float4(x)
1062 // float4(x) / float4(1) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -04001063 delete_right(&b, iter, outUpdated, outNeedsRescan);
1064 }
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001065 } else if (is_constant(left, 0)) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04001066 if (leftType.typeKind() == Type::TypeKind::kScalar &&
1067 rightType.typeKind() == Type::TypeKind::kVector &&
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001068 !right.hasSideEffects()) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -04001069 // 0 / float4(x) -> float4(0)
Ethan Nicholasfe53e582017-04-27 16:24:51 -04001070 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
1071 } else {
1072 // 0 / x -> 0
Ethan Nicholas5af9ea32017-07-28 15:19:46 -04001073 // float4(0) / x -> float4(0)
1074 // float4(0) / float4(x) -> float4(0)
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001075 if (!right.hasSideEffects()) {
Ethan Nicholas51493ee2017-12-11 12:34:33 -05001076 delete_right(&b, iter, outUpdated, outNeedsRescan);
1077 }
Ethan Nicholasfe53e582017-04-27 16:24:51 -04001078 }
1079 }
1080 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001081 case Token::Kind::TK_PLUSEQ:
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001082 if (is_constant(right, 0)) {
1083 clear_write(left);
Ethan Nicholasfe53e582017-04-27 16:24:51 -04001084 delete_right(&b, iter, outUpdated, outNeedsRescan);
1085 }
1086 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001087 case Token::Kind::TK_MINUSEQ:
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001088 if (is_constant(right, 0)) {
1089 clear_write(left);
Ethan Nicholasfe53e582017-04-27 16:24:51 -04001090 delete_right(&b, iter, outUpdated, outNeedsRescan);
1091 }
1092 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001093 case Token::Kind::TK_STAREQ:
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001094 if (is_constant(right, 1)) {
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_SLASHEQ:
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001100 if (is_constant(right, 1)) {
1101 clear_write(left);
Ethan Nicholascb670962017-04-20 19:31:52 -04001102 delete_right(&b, iter, outUpdated, outNeedsRescan);
1103 }
1104 break;
1105 default:
1106 break;
1107 }
Ethan Nicholas409f6f02019-09-17 12:34:39 -04001108 break;
1109 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001110 case Expression::Kind::kSwizzle: {
John Stiles403a3632020-08-20 12:11:48 -04001111 Swizzle& s = expr->as<Swizzle>();
Ethan Nicholas409f6f02019-09-17 12:34:39 -04001112 // detect identity swizzles like foo.rgba
Ethan Nicholas30d30222020-09-11 12:27:26 -04001113 if ((int) s.fComponents.size() == s.fBase->type().columns()) {
Ethan Nicholas409f6f02019-09-17 12:34:39 -04001114 bool identity = true;
1115 for (int i = 0; i < (int) s.fComponents.size(); ++i) {
1116 if (s.fComponents[i] != i) {
1117 identity = false;
1118 break;
1119 }
1120 }
1121 if (identity) {
1122 *outUpdated = true;
1123 if (!try_replace_expression(&b, iter, &s.fBase)) {
1124 *outNeedsRescan = true;
1125 return;
1126 }
John Stiles70025e52020-09-28 16:08:58 -04001127 SkASSERT((*iter)->isExpression());
Ethan Nicholas409f6f02019-09-17 12:34:39 -04001128 break;
1129 }
1130 }
1131 // detect swizzles of swizzles, e.g. replace foo.argb.r000 with foo.a000
Ethan Nicholase6592142020-09-08 10:22:09 -04001132 if (s.fBase->kind() == Expression::Kind::kSwizzle) {
John Stilesa5a97b42020-08-18 11:19:07 -04001133 Swizzle& base = s.fBase->as<Swizzle>();
Ethan Nicholas409f6f02019-09-17 12:34:39 -04001134 std::vector<int> final;
1135 for (int c : s.fComponents) {
Brian Osman25647672020-09-15 15:16:56 -04001136 final.push_back(base.fComponents[c]);
Ethan Nicholas409f6f02019-09-17 12:34:39 -04001137 }
1138 *outUpdated = true;
1139 std::unique_ptr<Expression> replacement(new Swizzle(*fContext, base.fBase->clone(),
1140 std::move(final)));
1141 if (!try_replace_expression(&b, iter, &replacement)) {
1142 *outNeedsRescan = true;
1143 return;
1144 }
John Stiles70025e52020-09-28 16:08:58 -04001145 SkASSERT((*iter)->isExpression());
Ethan Nicholas409f6f02019-09-17 12:34:39 -04001146 }
John Stiles30212b72020-06-11 17:55:07 -04001147 break;
Ethan Nicholascb670962017-04-20 19:31:52 -04001148 }
1149 default:
1150 break;
1151 }
1152}
1153
John Stiles92219b42020-06-15 12:32:24 -04001154// Returns true if this statement could potentially execute a break at the current level. We ignore
1155// nested loops and switches, since any breaks inside of them will merely break the loop / switch.
John Stilesb92641c2020-08-31 18:09:01 -04001156static bool contains_conditional_break(Statement& stmt) {
1157 class ContainsConditionalBreak : public ProgramVisitor {
1158 public:
1159 bool visitStatement(const Statement& stmt) override {
Ethan Nicholase6592142020-09-08 10:22:09 -04001160 switch (stmt.kind()) {
1161 case Statement::Kind::kBlock:
John Stilesb92641c2020-08-31 18:09:01 -04001162 return this->INHERITED::visitStatement(stmt);
1163
Ethan Nicholase6592142020-09-08 10:22:09 -04001164 case Statement::Kind::kBreak:
John Stilesb92641c2020-08-31 18:09:01 -04001165 return fInConditional > 0;
1166
Ethan Nicholase6592142020-09-08 10:22:09 -04001167 case Statement::Kind::kIf: {
John Stilesb92641c2020-08-31 18:09:01 -04001168 ++fInConditional;
1169 bool result = this->INHERITED::visitStatement(stmt);
1170 --fInConditional;
1171 return result;
1172 }
1173
1174 default:
1175 return false;
1176 }
1177 }
1178
1179 int fInConditional = 0;
1180 using INHERITED = ProgramVisitor;
1181 };
1182
1183 return ContainsConditionalBreak{}.visitStatement(stmt);
John Stiles92219b42020-06-15 12:32:24 -04001184}
1185
Ethan Nicholas5005a222018-08-24 13:06:27 -04001186// returns true if this statement definitely executes a break at the current level (we ignore
1187// nested loops and switches, since any breaks inside of them will merely break the loop / switch)
John Stilesb92641c2020-08-31 18:09:01 -04001188static bool contains_unconditional_break(Statement& stmt) {
1189 class ContainsUnconditionalBreak : public ProgramVisitor {
1190 public:
1191 bool visitStatement(const Statement& stmt) override {
Ethan Nicholase6592142020-09-08 10:22:09 -04001192 switch (stmt.kind()) {
1193 case Statement::Kind::kBlock:
John Stilesb92641c2020-08-31 18:09:01 -04001194 return this->INHERITED::visitStatement(stmt);
1195
Ethan Nicholase6592142020-09-08 10:22:09 -04001196 case Statement::Kind::kBreak:
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001197 return true;
John Stilesb92641c2020-08-31 18:09:01 -04001198
1199 default:
1200 return false;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001201 }
John Stilesb92641c2020-08-31 18:09:01 -04001202 }
John Stiles92219b42020-06-15 12:32:24 -04001203
John Stilesb92641c2020-08-31 18:09:01 -04001204 using INHERITED = ProgramVisitor;
1205 };
John Stiles92219b42020-06-15 12:32:24 -04001206
John Stilesb92641c2020-08-31 18:09:01 -04001207 return ContainsUnconditionalBreak{}.visitStatement(stmt);
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001208}
1209
John Stiles92219b42020-06-15 12:32:24 -04001210static void move_all_but_break(std::unique_ptr<Statement>& stmt,
1211 std::vector<std::unique_ptr<Statement>>* target) {
Ethan Nicholase6592142020-09-08 10:22:09 -04001212 switch (stmt->kind()) {
1213 case Statement::Kind::kBlock: {
John Stiles92219b42020-06-15 12:32:24 -04001214 // Recurse into the block.
1215 Block& block = static_cast<Block&>(*stmt);
1216
1217 std::vector<std::unique_ptr<Statement>> blockStmts;
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001218 blockStmts.reserve(block.children().size());
1219 for (std::unique_ptr<Statement>& stmt : block.children()) {
1220 move_all_but_break(stmt, &blockStmts);
Ethan Nicholas739e1ca2020-06-11 12:16:14 -04001221 }
John Stiles92219b42020-06-15 12:32:24 -04001222
1223 target->push_back(std::make_unique<Block>(block.fOffset, std::move(blockStmts),
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001224 block.symbolTable(), block.isScope()));
Ethan Nicholas739e1ca2020-06-11 12:16:14 -04001225 break;
John Stiles92219b42020-06-15 12:32:24 -04001226 }
1227
Ethan Nicholase6592142020-09-08 10:22:09 -04001228 case Statement::Kind::kBreak:
John Stiles92219b42020-06-15 12:32:24 -04001229 // Do not append a break to the target.
1230 break;
1231
Ethan Nicholas739e1ca2020-06-11 12:16:14 -04001232 default:
John Stiles92219b42020-06-15 12:32:24 -04001233 // Append normal statements to the target.
1234 target->push_back(std::move(stmt));
1235 break;
Ethan Nicholas739e1ca2020-06-11 12:16:14 -04001236 }
1237}
1238
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001239// Returns a block containing all of the statements that will be run if the given case matches
1240// (which, owing to the statements being owned by unique_ptrs, means the switch itself will be
1241// broken by this call and must then be discarded).
1242// Returns null (and leaves the switch unmodified) if no such simple reduction is possible, such as
1243// when break statements appear inside conditionals.
John Stiles92219b42020-06-15 12:32:24 -04001244static std::unique_ptr<Statement> block_for_case(SwitchStatement* switchStatement,
1245 SwitchCase* caseToCapture) {
1246 // We have to be careful to not move any of the pointers until after we're sure we're going to
1247 // succeed, so before we make any changes at all, we check the switch-cases to decide on a plan
1248 // of action. First, find the switch-case we are interested in.
1249 auto iter = switchStatement->fCases.begin();
1250 for (; iter != switchStatement->fCases.end(); ++iter) {
1251 if (iter->get() == caseToCapture) {
1252 break;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001253 }
John Stiles92219b42020-06-15 12:32:24 -04001254 }
1255
1256 // Next, walk forward through the rest of the switch. If we find a conditional break, we're
1257 // stuck and can't simplify at all. If we find an unconditional break, we have a range of
1258 // statements that we can use for simplification.
1259 auto startIter = iter;
1260 Statement* unconditionalBreakStmt = nullptr;
1261 for (; iter != switchStatement->fCases.end(); ++iter) {
1262 for (std::unique_ptr<Statement>& stmt : (*iter)->fStatements) {
1263 if (contains_conditional_break(*stmt)) {
1264 // We can't reduce switch-cases to a block when they have conditional breaks.
1265 return nullptr;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001266 }
John Stiles92219b42020-06-15 12:32:24 -04001267
1268 if (contains_unconditional_break(*stmt)) {
1269 // We found an unconditional break. We can use this block, but we need to strip
1270 // out the break statement.
1271 unconditionalBreakStmt = stmt.get();
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001272 break;
1273 }
1274 }
John Stiles92219b42020-06-15 12:32:24 -04001275
1276 if (unconditionalBreakStmt != nullptr) {
1277 break;
1278 }
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001279 }
John Stiles92219b42020-06-15 12:32:24 -04001280
1281 // We fell off the bottom of the switch or encountered a break. We know the range of statements
1282 // that we need to move over, and we know it's safe to do so.
1283 std::vector<std::unique_ptr<Statement>> caseStmts;
1284
1285 // We can move over most of the statements as-is.
1286 while (startIter != iter) {
1287 for (std::unique_ptr<Statement>& stmt : (*startIter)->fStatements) {
1288 caseStmts.push_back(std::move(stmt));
1289 }
1290 ++startIter;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001291 }
John Stiles92219b42020-06-15 12:32:24 -04001292
1293 // If we found an unconditional break at the end, we need to move what we can while avoiding
1294 // that break.
1295 if (unconditionalBreakStmt != nullptr) {
1296 for (std::unique_ptr<Statement>& stmt : (*startIter)->fStatements) {
1297 if (stmt.get() == unconditionalBreakStmt) {
1298 move_all_but_break(stmt, &caseStmts);
1299 unconditionalBreakStmt = nullptr;
1300 break;
1301 }
1302
1303 caseStmts.push_back(std::move(stmt));
1304 }
1305 }
1306
1307 SkASSERT(unconditionalBreakStmt == nullptr); // Verify that we fixed the unconditional break.
1308
1309 // Return our newly-synthesized block.
1310 return std::make_unique<Block>(/*offset=*/-1, std::move(caseStmts), switchStatement->fSymbols);
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001311}
1312
Ethan Nicholascb670962017-04-20 19:31:52 -04001313void Compiler::simplifyStatement(DefinitionMap& definitions,
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001314 BasicBlock& b,
1315 std::vector<BasicBlock::Node>::iterator* iter,
1316 std::unordered_set<const Variable*>* undefinedVariables,
1317 bool* outUpdated,
1318 bool* outNeedsRescan) {
Ethan Nicholascb670962017-04-20 19:31:52 -04001319 Statement* stmt = (*iter)->statement()->get();
Ethan Nicholase6592142020-09-08 10:22:09 -04001320 switch (stmt->kind()) {
1321 case Statement::Kind::kVarDeclaration: {
John Stilesa5a97b42020-08-18 11:19:07 -04001322 const auto& varDecl = stmt->as<VarDeclaration>();
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001323 if (varDecl.fVar->dead() &&
1324 (!varDecl.fValue ||
1325 !varDecl.fValue->hasSideEffects())) {
1326 if (varDecl.fValue) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001327 SkASSERT((*iter)->statement()->get() == stmt);
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001328 if (!b.tryRemoveExpressionBefore(iter, varDecl.fValue.get())) {
1329 *outNeedsRescan = true;
Ethan Nicholascb670962017-04-20 19:31:52 -04001330 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001331 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001332 (*iter)->setStatement(std::unique_ptr<Statement>(new Nop()));
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001333 *outUpdated = true;
Ethan Nicholascb670962017-04-20 19:31:52 -04001334 }
1335 break;
1336 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001337 case Statement::Kind::kIf: {
John Stilesa5a97b42020-08-18 11:19:07 -04001338 IfStatement& i = stmt->as<IfStatement>();
Ethan Nicholase6592142020-09-08 10:22:09 -04001339 if (i.fTest->kind() == Expression::Kind::kBoolLiteral) {
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001340 // constant if, collapse down to a single branch
Ethan Nicholas59d660c2020-09-28 09:18:15 -04001341 if (i.fTest->as<BoolLiteral>().value()) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001342 SkASSERT(i.fIfTrue);
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001343 (*iter)->setStatement(std::move(i.fIfTrue));
1344 } else {
1345 if (i.fIfFalse) {
1346 (*iter)->setStatement(std::move(i.fIfFalse));
1347 } else {
1348 (*iter)->setStatement(std::unique_ptr<Statement>(new Nop()));
1349 }
1350 }
1351 *outUpdated = true;
1352 *outNeedsRescan = true;
1353 break;
1354 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001355 if (i.fIfFalse && i.fIfFalse->isEmpty()) {
1356 // else block doesn't do anything, remove it
1357 i.fIfFalse.reset();
1358 *outUpdated = true;
1359 *outNeedsRescan = true;
1360 }
1361 if (!i.fIfFalse && i.fIfTrue->isEmpty()) {
1362 // if block doesn't do anything, no else block
1363 if (i.fTest->hasSideEffects()) {
1364 // test has side effects, keep it
1365 (*iter)->setStatement(std::unique_ptr<Statement>(
1366 new ExpressionStatement(std::move(i.fTest))));
1367 } else {
1368 // no if, no else, no test side effects, kill the whole if
1369 // statement
1370 (*iter)->setStatement(std::unique_ptr<Statement>(new Nop()));
1371 }
1372 *outUpdated = true;
1373 *outNeedsRescan = true;
1374 }
1375 break;
1376 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001377 case Statement::Kind::kSwitch: {
John Stilesa5a97b42020-08-18 11:19:07 -04001378 SwitchStatement& s = stmt->as<SwitchStatement>();
Ethan Nicholas34b19c52020-09-14 11:33:47 -04001379 int64_t switchValue;
1380 if (fIRGenerator->getConstantInt(*s.fValue, &switchValue)) {
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001381 // switch is constant, replace it with the case that matches
1382 bool found = false;
1383 SwitchCase* defaultCase = nullptr;
John Stiles9d944232020-08-19 09:56:49 -04001384 for (const std::unique_ptr<SwitchCase>& c : s.fCases) {
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001385 if (!c->fValue) {
1386 defaultCase = c.get();
1387 continue;
1388 }
Ethan Nicholas34b19c52020-09-14 11:33:47 -04001389 int64_t caseValue;
1390 SkAssertResult(fIRGenerator->getConstantInt(*c->fValue, &caseValue));
1391 if (caseValue == switchValue) {
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001392 std::unique_ptr<Statement> newBlock = block_for_case(&s, c.get());
1393 if (newBlock) {
1394 (*iter)->setStatement(std::move(newBlock));
John Stiles9d944232020-08-19 09:56:49 -04001395 found = true;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001396 break;
1397 } else {
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -04001398 if (s.fIsStatic && !(fFlags & kPermitInvalidStaticTests_Flag)) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001399 this->error(s.fOffset,
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001400 "static switch contains non-static conditional break");
1401 s.fIsStatic = false;
1402 }
1403 return; // can't simplify
1404 }
1405 }
1406 }
1407 if (!found) {
1408 // no matching case. use default if it exists, or kill the whole thing
1409 if (defaultCase) {
1410 std::unique_ptr<Statement> newBlock = block_for_case(&s, defaultCase);
1411 if (newBlock) {
1412 (*iter)->setStatement(std::move(newBlock));
1413 } else {
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -04001414 if (s.fIsStatic && !(fFlags & kPermitInvalidStaticTests_Flag)) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001415 this->error(s.fOffset,
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001416 "static switch contains non-static conditional break");
1417 s.fIsStatic = false;
1418 }
1419 return; // can't simplify
1420 }
1421 } else {
1422 (*iter)->setStatement(std::unique_ptr<Statement>(new Nop()));
1423 }
1424 }
1425 *outUpdated = true;
1426 *outNeedsRescan = true;
1427 }
1428 break;
1429 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001430 case Statement::Kind::kExpression: {
John Stilesa5a97b42020-08-18 11:19:07 -04001431 ExpressionStatement& e = stmt->as<ExpressionStatement>();
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001432 SkASSERT((*iter)->statement()->get() == &e);
Ethan Nicholasd503a5a2020-09-30 09:29:55 -04001433 if (!e.expression()->hasSideEffects()) {
Ethan Nicholascb670962017-04-20 19:31:52 -04001434 // Expression statement with no side effects, kill it
Ethan Nicholasd503a5a2020-09-30 09:29:55 -04001435 if (!b.tryRemoveExpressionBefore(iter, e.expression().get())) {
Ethan Nicholascb670962017-04-20 19:31:52 -04001436 *outNeedsRescan = true;
1437 }
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001438 SkASSERT((*iter)->statement()->get() == stmt);
Ethan Nicholascb670962017-04-20 19:31:52 -04001439 (*iter)->setStatement(std::unique_ptr<Statement>(new Nop()));
1440 *outUpdated = true;
1441 }
1442 break;
1443 }
1444 default:
1445 break;
1446 }
1447}
1448
John Stiles0cc193a2020-09-09 09:39:34 -04001449bool Compiler::scanCFG(FunctionDefinition& f) {
1450 bool madeChanges = false;
1451
Ethan Nicholascb670962017-04-20 19:31:52 -04001452 CFG cfg = CFGGenerator().getCFG(f);
1453 this->computeDataFlow(&cfg);
ethannicholas22f939e2016-10-13 13:25:34 -07001454
1455 // check for unreachable code
1456 for (size_t i = 0; i < cfg.fBlocks.size(); i++) {
John Stiles0cc193a2020-09-09 09:39:34 -04001457 const BasicBlock& block = cfg.fBlocks[i];
John Stiles61e75e32020-10-01 15:42:37 -04001458 if (i != cfg.fStart && !block.fIsReachable && block.fNodes.size()) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001459 int offset;
John Stiles0cc193a2020-09-09 09:39:34 -04001460 const BasicBlock::Node& node = block.fNodes[0];
John Stiles70025e52020-09-28 16:08:58 -04001461 if (node.isStatement()) {
1462 offset = (*node.statement())->fOffset;
1463 } else {
1464 offset = (*node.expression())->fOffset;
1465 if ((*node.expression())->is<BoolLiteral>()) {
1466 // Function inlining can generate do { ... } while(false) loops which always
1467 // break, so the boolean condition is considered unreachable. Since not being
1468 // able to reach a literal is a non-issue in the first place, we don't report an
1469 // error in this case.
1470 continue;
1471 }
Ethan Nicholas86a43402017-01-19 13:32:00 -05001472 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001473 this->error(offset, String("unreachable"));
ethannicholas22f939e2016-10-13 13:25:34 -07001474 }
1475 }
1476 if (fErrorCount) {
John Stiles0cc193a2020-09-09 09:39:34 -04001477 return madeChanges;
ethannicholas22f939e2016-10-13 13:25:34 -07001478 }
1479
Ethan Nicholascb670962017-04-20 19:31:52 -04001480 // check for dead code & undefined variables, perform constant propagation
1481 std::unordered_set<const Variable*> undefinedVariables;
1482 bool updated;
1483 bool needsRescan = false;
1484 do {
1485 if (needsRescan) {
1486 cfg = CFGGenerator().getCFG(f);
1487 this->computeDataFlow(&cfg);
1488 needsRescan = false;
Ethan Nicholas113628d2017-02-02 16:11:39 -05001489 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001490
1491 updated = false;
Ethan Nicholas1de14812020-06-19 15:32:49 -04001492 bool first = true;
Ethan Nicholascb670962017-04-20 19:31:52 -04001493 for (BasicBlock& b : cfg.fBlocks) {
John Stiles61e75e32020-10-01 15:42:37 -04001494 if (!first && !b.fIsReachable) {
Ethan Nicholas1de14812020-06-19 15:32:49 -04001495 // Block was reachable before optimization, but has since become unreachable. In
1496 // addition to being dead code, it's broken - since control flow can't reach it, no
1497 // prior variable definitions can reach it, and therefore variables might look to
1498 // have not been properly assigned. Kill it.
Brian Osmandb16c482020-09-09 15:15:06 -04001499
1500 // We need to do this in two steps. For any variable declarations, the node list
1501 // will contain statement nodes for each VarDeclaration, and then a statement for
1502 // the VarDeclarationsStatement. When we replace the VDS with a Nop, we delete the
1503 // storage of the unique_ptr that the VD nodes are pointing to. So we remove those
1504 // from the node list entirely, first.
John Stiles70025e52020-09-28 16:08:58 -04001505 b.fNodes.erase(std::remove_if(b.fNodes.begin(), b.fNodes.end(),
1506 [](const BasicBlock::Node& node) {
1507 return node.isStatement() &&
1508 (*node.statement())->is<VarDeclaration>();
1509 }),
1510 b.fNodes.end());
Brian Osmandb16c482020-09-09 15:15:06 -04001511
1512 // Now replace any remaining statements in the block with Nops.
Ethan Nicholas1de14812020-06-19 15:32:49 -04001513 for (BasicBlock::Node& node : b.fNodes) {
John Stiles70025e52020-09-28 16:08:58 -04001514 if (node.isStatement() && !(*node.statement())->is<Nop>()) {
John Stiles0cc193a2020-09-09 09:39:34 -04001515 node.setStatement(std::make_unique<Nop>());
1516 madeChanges = true;
Ethan Nicholas1de14812020-06-19 15:32:49 -04001517 }
1518 }
1519 continue;
1520 }
1521 first = false;
Ethan Nicholascb670962017-04-20 19:31:52 -04001522 DefinitionMap definitions = b.fBefore;
1523
1524 for (auto iter = b.fNodes.begin(); iter != b.fNodes.end() && !needsRescan; ++iter) {
John Stiles70025e52020-09-28 16:08:58 -04001525 if (iter->isExpression()) {
Ethan Nicholascb670962017-04-20 19:31:52 -04001526 this->simplifyExpression(definitions, b, &iter, &undefinedVariables, &updated,
1527 &needsRescan);
1528 } else {
1529 this->simplifyStatement(definitions, b, &iter, &undefinedVariables, &updated,
John Stiles0cc193a2020-09-09 09:39:34 -04001530 &needsRescan);
Ethan Nicholascb670962017-04-20 19:31:52 -04001531 }
Ethan Nicholas4b330df2017-05-17 10:52:55 -04001532 if (needsRescan) {
1533 break;
1534 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001535 this->addDefinitions(*iter, &definitions);
1536 }
Brian Osman01a3eb42020-09-14 11:32:49 -04001537
1538 if (needsRescan) {
1539 break;
1540 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001541 }
John Stiles0cc193a2020-09-09 09:39:34 -04001542 madeChanges |= updated;
Ethan Nicholascb670962017-04-20 19:31:52 -04001543 } while (updated);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001544 SkASSERT(!needsRescan);
ethannicholas22f939e2016-10-13 13:25:34 -07001545
Ethan Nicholas91a10532017-06-22 11:24:38 -04001546 // verify static ifs & switches, clean up dead variable decls
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001547 for (BasicBlock& b : cfg.fBlocks) {
1548 DefinitionMap definitions = b.fBefore;
1549
Ethan Nicholas91a10532017-06-22 11:24:38 -04001550 for (auto iter = b.fNodes.begin(); iter != b.fNodes.end() && !needsRescan;) {
John Stiles70025e52020-09-28 16:08:58 -04001551 if (iter->isStatement()) {
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001552 const Statement& s = **iter->statement();
Ethan Nicholase6592142020-09-08 10:22:09 -04001553 switch (s.kind()) {
1554 case Statement::Kind::kIf:
John Stilesa5a97b42020-08-18 11:19:07 -04001555 if (s.as<IfStatement>().fIsStatic &&
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -04001556 !(fFlags & kPermitInvalidStaticTests_Flag)) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001557 this->error(s.fOffset, "static if has non-static test");
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001558 }
Ethan Nicholas91a10532017-06-22 11:24:38 -04001559 ++iter;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001560 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001561 case Statement::Kind::kSwitch:
John Stilesa5a97b42020-08-18 11:19:07 -04001562 if (s.as<SwitchStatement>().fIsStatic &&
John Stiles0cc193a2020-09-09 09:39:34 -04001563 !(fFlags & kPermitInvalidStaticTests_Flag)) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001564 this->error(s.fOffset, "static switch has non-static test");
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001565 }
Ethan Nicholas91a10532017-06-22 11:24:38 -04001566 ++iter;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001567 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001568 case Statement::Kind::kVarDeclarations: {
John Stilesa5a97b42020-08-18 11:19:07 -04001569 VarDeclarations& decls = *s.as<VarDeclarationsStatement>().fDeclaration;
John Stiles0cc193a2020-09-09 09:39:34 -04001570 decls.fVars.erase(
1571 std::remove_if(decls.fVars.begin(), decls.fVars.end(),
1572 [&](const std::unique_ptr<Statement>& var) {
1573 bool nop = var->is<Nop>();
1574 madeChanges |= nop;
1575 return nop;
1576 }),
1577 decls.fVars.end());
1578 if (decls.fVars.empty()) {
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001579 iter = b.fNodes.erase(iter);
1580 } else {
1581 ++iter;
1582 }
1583 break;
1584 }
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001585 default:
Ethan Nicholas91a10532017-06-22 11:24:38 -04001586 ++iter;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001587 break;
1588 }
Ethan Nicholas91a10532017-06-22 11:24:38 -04001589 } else {
1590 ++iter;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001591 }
1592 }
1593 }
1594
ethannicholas22f939e2016-10-13 13:25:34 -07001595 // check for missing return
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001596 if (f.fDeclaration.fReturnType != *fContext->fVoid_Type) {
John Stiles61e75e32020-10-01 15:42:37 -04001597 if (cfg.fBlocks[cfg.fExit].fIsReachable) {
Brian Osman58384ad2020-10-02 22:15:22 +00001598 this->error(f.fOffset, String("function '" + String(f.fDeclaration.fName) +
Ethan Nicholasdb80f692019-11-22 14:06:12 -05001599 "' can exit without returning a value"));
ethannicholas22f939e2016-10-13 13:25:34 -07001600 }
1601 }
John Stiles0cc193a2020-09-09 09:39:34 -04001602
1603 return madeChanges;
ethannicholas22f939e2016-10-13 13:25:34 -07001604}
1605
Brian Osman32d53552020-09-23 13:55:20 -04001606std::unique_ptr<Program> Compiler::convertProgram(
1607 Program::Kind kind,
1608 String text,
1609 const Program::Settings& settings,
1610 const std::vector<std::unique_ptr<ExternalValue>>* externalValues) {
1611 SkASSERT(!externalValues || (kind == Program::kGeneric_Kind));
Ethan Nicholas91164d12019-05-15 15:29:54 -04001612
ethannicholasb3058bd2016-07-01 08:22:01 -07001613 fErrorText = "";
1614 fErrorCount = 0;
John Stiles7b463002020-08-31 17:29:21 -04001615 fInliner.reset(context(), settings);
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001616 std::vector<std::unique_ptr<ProgramElement>>* inherited;
ethannicholasd598f792016-07-25 10:08:54 -07001617 std::vector<std::unique_ptr<ProgramElement>> elements;
ethannicholasb3058bd2016-07-01 08:22:01 -07001618 switch (kind) {
1619 case Program::kVertex_Kind:
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001620 inherited = &fVertexInclude;
John Stiles810c8cf2020-08-26 19:46:27 -04001621 fIRGenerator->fIntrinsics = fGPUIntrinsics.get();
Brian Osmane498b3c2020-09-23 14:42:11 -04001622 fIRGenerator->start(&settings, fVertexSymbolTable, inherited);
ethannicholasb3058bd2016-07-01 08:22:01 -07001623 break;
1624 case Program::kFragment_Kind:
Brian Osman00a8b5b2020-10-02 09:06:04 -04001625 inherited = nullptr;
1626 fIRGenerator->fIntrinsics = fFragmentIntrinsics.get();
1627 fIRGenerator->start(&settings, fFragmentSymbolTable, /*inherited=*/nullptr);
ethannicholasb3058bd2016-07-01 08:22:01 -07001628 break;
Ethan Nicholas52cad152017-02-16 16:37:32 -05001629 case Program::kGeometry_Kind:
Ethan Nicholasc18bb512020-07-28 14:46:53 -04001630 this->loadGeometryIntrinsics();
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001631 inherited = &fGeometryInclude;
John Stiles810c8cf2020-08-26 19:46:27 -04001632 fIRGenerator->fIntrinsics = fGPUIntrinsics.get();
Brian Osmane498b3c2020-09-23 14:42:11 -04001633 fIRGenerator->start(&settings, fGeometrySymbolTable, inherited);
Ethan Nicholas52cad152017-02-16 16:37:32 -05001634 break;
Brian Osman8e2ef022020-09-30 13:26:43 -04001635 case Program::kFragmentProcessor_Kind:
1636 this->loadFPIntrinsics();
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001637 inherited = nullptr;
Brian Osman8e2ef022020-09-30 13:26:43 -04001638 fIRGenerator->fIntrinsics = fFPIntrinsics.get();
1639 fIRGenerator->start(&settings, fFPSymbolTable, /*inherited=*/nullptr);
Ethan Nicholas762466e2017-06-29 10:03:38 -04001640 break;
Ethan Nicholas8da1e652019-05-24 11:01:59 -04001641 case Program::kPipelineStage_Kind:
Ethan Nicholasc18bb512020-07-28 14:46:53 -04001642 this->loadPipelineIntrinsics();
Brian Osman8e2ef022020-09-30 13:26:43 -04001643 inherited = nullptr;
1644 fIRGenerator->fIntrinsics = fPipelineIntrinsics.get();
1645 fIRGenerator->start(&settings, fPipelineSymbolTable, /*inherited=*/nullptr);
Ethan Nicholas8da1e652019-05-24 11:01:59 -04001646 break;
Ethan Nicholas746035a2019-04-23 13:31:09 -04001647 case Program::kGeneric_Kind:
Ethan Nicholasc18bb512020-07-28 14:46:53 -04001648 this->loadInterpreterIntrinsics();
Brian Osmaneac49832020-09-18 11:49:22 -04001649 inherited = nullptr;
John Stiles810c8cf2020-08-26 19:46:27 -04001650 fIRGenerator->fIntrinsics = fInterpreterIntrinsics.get();
Brian Osmane498b3c2020-09-23 14:42:11 -04001651 fIRGenerator->start(&settings, fInterpreterSymbolTable, /*inherited=*/nullptr);
Ethan Nicholas0d997662019-04-08 09:46:01 -04001652 break;
ethannicholasb3058bd2016-07-01 08:22:01 -07001653 }
Brian Osman32d53552020-09-23 13:55:20 -04001654 if (externalValues) {
1655 // Add any external values to the symbol table. IRGenerator::start() has pushed a table, so
1656 // we're only making these visible to the current Program.
1657 for (const auto& ev : *externalValues) {
Brian Osman58384ad2020-10-02 22:15:22 +00001658 fIRGenerator->fSymbolTable->addWithoutOwnership(ev->fName, ev.get());
Brian Osman32d53552020-09-23 13:55:20 -04001659 }
1660 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001661 std::unique_ptr<String> textPtr(new String(std::move(text)));
1662 fSource = textPtr.get();
Ethan Nicholasc18bb512020-07-28 14:46:53 -04001663 fIRGenerator->convertProgram(kind, textPtr->c_str(), textPtr->size(), &elements);
John Stilesfbd050b2020-08-03 13:21:46 -04001664 auto result = std::make_unique<Program>(kind,
1665 std::move(textPtr),
1666 settings,
1667 fContext,
1668 inherited,
1669 std::move(elements),
1670 fIRGenerator->fSymbolTable,
1671 fIRGenerator->fInputs);
Brian Osmane498b3c2020-09-23 14:42:11 -04001672 fIRGenerator->finish();
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001673 if (fErrorCount) {
1674 return nullptr;
1675 }
Ethan Nicholas34b19c52020-09-14 11:33:47 -04001676 if (settings.fOptimize && !this->optimize(*result)) {
1677 return nullptr;
1678 }
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001679 return result;
1680}
1681
Ethan Nicholas00543112018-07-31 09:44:36 -04001682bool Compiler::optimize(Program& program) {
1683 SkASSERT(!fErrorCount);
Ethan Nicholas34b19c52020-09-14 11:33:47 -04001684 fIRGenerator->fKind = program.fKind;
1685 fIRGenerator->fSettings = &program.fSettings;
John Stiles7954d6c2020-09-01 10:53:02 -04001686
Ethan Nicholas34b19c52020-09-14 11:33:47 -04001687 while (fErrorCount == 0) {
1688 bool madeChanges = false;
John Stiles7954d6c2020-09-01 10:53:02 -04001689
Ethan Nicholas34b19c52020-09-14 11:33:47 -04001690 // Scan and optimize based on the control-flow graph for each function.
1691 for (ProgramElement& element : program) {
1692 if (element.is<FunctionDefinition>()) {
1693 madeChanges |= this->scanCFG(element.as<FunctionDefinition>());
1694 }
1695 }
1696
1697 // Perform inline-candidate analysis and inline any functions deemed suitable.
John Stiles881a10c2020-09-19 10:13:24 -04001698 madeChanges |= fInliner.analyze(program);
Ethan Nicholas34b19c52020-09-14 11:33:47 -04001699
1700 // Remove dead functions. We wait until after analysis so that we still report errors,
1701 // even in unused code.
1702 if (program.fSettings.fRemoveDeadFunctions) {
1703 program.fElements.erase(
1704 std::remove_if(program.fElements.begin(),
1705 program.fElements.end(),
1706 [&](const std::unique_ptr<ProgramElement>& element) {
1707 if (!element->is<FunctionDefinition>()) {
1708 return false;
1709 }
1710 const auto& fn = element->as<FunctionDefinition>();
1711 bool dead = fn.fDeclaration.fCallCount == 0 &&
Brian Osman58384ad2020-10-02 22:15:22 +00001712 fn.fDeclaration.fName != "main";
Ethan Nicholas34b19c52020-09-14 11:33:47 -04001713 madeChanges |= dead;
1714 return dead;
1715 }),
1716 program.fElements.end());
1717 }
1718
1719 if (program.fKind != Program::kFragmentProcessor_Kind) {
1720 // Remove dead variables.
John Stileseadfc3b2020-09-02 14:12:41 -04001721 for (ProgramElement& element : program) {
Ethan Nicholas34b19c52020-09-14 11:33:47 -04001722 if (!element.is<VarDeclarations>()) {
1723 continue;
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001724 }
Ethan Nicholas34b19c52020-09-14 11:33:47 -04001725 VarDeclarations& vars = element.as<VarDeclarations>();
1726 vars.fVars.erase(
1727 std::remove_if(vars.fVars.begin(), vars.fVars.end(),
1728 [&](const std::unique_ptr<Statement>& stmt) {
1729 bool dead = stmt->as<VarDeclaration>().fVar->dead();
John Stiles73a6bff2020-09-09 13:40:37 -04001730 madeChanges |= dead;
1731 return dead;
1732 }),
Ethan Nicholas34b19c52020-09-14 11:33:47 -04001733 vars.fVars.end());
John Stiles73a6bff2020-09-09 13:40:37 -04001734 }
1735
Ethan Nicholas34b19c52020-09-14 11:33:47 -04001736 // Remove empty variable declarations with no variables left inside of them.
1737 program.fElements.erase(
1738 std::remove_if(program.fElements.begin(), program.fElements.end(),
1739 [&](const std::unique_ptr<ProgramElement>& element) {
1740 if (!element->is<VarDeclarations>()) {
1741 return false;
1742 }
1743 bool dead = element->as<VarDeclarations>().fVars.empty();
1744 madeChanges |= dead;
1745 return dead;
1746 }),
1747 program.fElements.end());
1748 }
John Stiles73a6bff2020-09-09 13:40:37 -04001749
Ethan Nicholas34b19c52020-09-14 11:33:47 -04001750 if (!madeChanges) {
1751 break;
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001752 }
Ethan Nicholas00543112018-07-31 09:44:36 -04001753 }
1754 return fErrorCount == 0;
1755}
1756
Brian Osmanfb32ddf2019-06-18 10:14:20 -04001757#if defined(SKSL_STANDALONE) || SK_SUPPORT_GPU
1758
Ethan Nicholas00543112018-07-31 09:44:36 -04001759bool Compiler::toSPIRV(Program& program, OutputStream& out) {
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001760#ifdef SK_ENABLE_SPIRV_VALIDATION
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001761 StringStream buffer;
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001762 fSource = program.fSource.get();
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001763 SPIRVCodeGenerator cg(fContext.get(), &program, this, &buffer);
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001764 bool result = cg.generateCode();
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001765 fSource = nullptr;
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001766 if (result) {
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001767 spvtools::SpirvTools tools(SPV_ENV_VULKAN_1_0);
Ethan Nicholas762466e2017-06-29 10:03:38 -04001768 const String& data = buffer.str();
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001769 SkASSERT(0 == data.size() % 4);
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001770 auto dumpmsg = [](spv_message_level_t, const char*, const spv_position_t&, const char* m) {
1771 SkDebugf("SPIR-V validation error: %s\n", m);
1772 };
1773 tools.SetMessageConsumer(dumpmsg);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001774 // Verify that the SPIR-V we produced is valid. If this SkASSERT fails, check the logs prior
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001775 // to the failure to see the validation errors.
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001776 SkAssertResult(tools.Validate((const uint32_t*) data.c_str(), data.size() / 4));
Ethan Nicholas762466e2017-06-29 10:03:38 -04001777 out.write(data.c_str(), data.size());
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001778 }
1779#else
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001780 fSource = program.fSource.get();
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001781 SPIRVCodeGenerator cg(fContext.get(), &program, this, &out);
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001782 bool result = cg.generateCode();
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001783 fSource = nullptr;
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001784#endif
Ethan Nicholasce33f102016-12-09 17:22:59 -05001785 return result;
1786}
1787
Ethan Nicholas00543112018-07-31 09:44:36 -04001788bool Compiler::toSPIRV(Program& program, String* out) {
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001789 StringStream buffer;
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001790 bool result = this->toSPIRV(program, buffer);
1791 if (result) {
Ethan Nicholas762466e2017-06-29 10:03:38 -04001792 *out = buffer.str();
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001793 }
1794 return result;
1795}
1796
Ethan Nicholas00543112018-07-31 09:44:36 -04001797bool Compiler::toGLSL(Program& program, OutputStream& out) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001798 fSource = program.fSource.get();
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001799 GLSLCodeGenerator cg(fContext.get(), &program, this, &out);
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001800 bool result = cg.generateCode();
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001801 fSource = nullptr;
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001802 return result;
1803}
1804
Ethan Nicholas00543112018-07-31 09:44:36 -04001805bool Compiler::toGLSL(Program& program, String* out) {
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001806 StringStream buffer;
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001807 bool result = this->toGLSL(program, buffer);
1808 if (result) {
Ethan Nicholas762466e2017-06-29 10:03:38 -04001809 *out = buffer.str();
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001810 }
1811 return result;
1812}
1813
Brian Osmanc0243912020-02-19 15:35:26 -05001814bool Compiler::toHLSL(Program& program, String* out) {
1815 String spirv;
1816 if (!this->toSPIRV(program, &spirv)) {
1817 return false;
1818 }
1819
1820 return SPIRVtoHLSL(spirv, out);
1821}
1822
Ethan Nicholas00543112018-07-31 09:44:36 -04001823bool Compiler::toMetal(Program& program, OutputStream& out) {
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001824 MetalCodeGenerator cg(fContext.get(), &program, this, &out);
Ethan Nicholascc305772017-10-13 16:17:45 -04001825 bool result = cg.generateCode();
Ethan Nicholascc305772017-10-13 16:17:45 -04001826 return result;
1827}
1828
Ethan Nicholas00543112018-07-31 09:44:36 -04001829bool Compiler::toMetal(Program& program, String* out) {
Timothy Liangb8eeb802018-07-23 16:46:16 -04001830 StringStream buffer;
1831 bool result = this->toMetal(program, buffer);
1832 if (result) {
1833 *out = buffer.str();
1834 }
1835 return result;
1836}
1837
Greg Daniela28ea672020-09-25 11:12:56 -04001838#if defined(SKSL_STANDALONE) || GR_TEST_UTILS
Ethan Nicholas00543112018-07-31 09:44:36 -04001839bool Compiler::toCPP(Program& program, String name, OutputStream& out) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001840 fSource = program.fSource.get();
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001841 CPPCodeGenerator cg(fContext.get(), &program, this, name, &out);
Ethan Nicholas762466e2017-06-29 10:03:38 -04001842 bool result = cg.generateCode();
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001843 fSource = nullptr;
Ethan Nicholas762466e2017-06-29 10:03:38 -04001844 return result;
1845}
1846
Ethan Nicholas00543112018-07-31 09:44:36 -04001847bool Compiler::toH(Program& program, String name, OutputStream& out) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001848 fSource = program.fSource.get();
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001849 HCodeGenerator cg(fContext.get(), &program, this, name, &out);
Ethan Nicholas762466e2017-06-29 10:03:38 -04001850 bool result = cg.generateCode();
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001851 fSource = nullptr;
Ethan Nicholas00543112018-07-31 09:44:36 -04001852 return result;
1853}
Greg Daniela28ea672020-09-25 11:12:56 -04001854#endif // defined(SKSL_STANDALONE) || GR_TEST_UTILS
Ethan Nicholas00543112018-07-31 09:44:36 -04001855
Ethan Nicholas2a479a52020-08-18 16:29:45 -04001856#endif // defined(SKSL_STANDALONE) || SK_SUPPORT_GPU
Brian Osman2e29ab52019-09-20 12:19:11 -04001857
1858#if !defined(SKSL_STANDALONE) && SK_SUPPORT_GPU
Brian Osmana4b91692020-08-10 14:26:16 -04001859bool Compiler::toPipelineStage(Program& program, PipelineStageArgs* outArgs) {
Ethan Nicholas00543112018-07-31 09:44:36 -04001860 fSource = program.fSource.get();
1861 StringStream buffer;
Brian Osman300fe1d2020-01-23 15:42:43 -05001862 PipelineStageCodeGenerator cg(fContext.get(), &program, this, &buffer, outArgs);
Ethan Nicholas00543112018-07-31 09:44:36 -04001863 bool result = cg.generateCode();
1864 fSource = nullptr;
1865 if (result) {
Brian Osman107c6662019-12-30 15:02:30 -05001866 outArgs->fCode = buffer.str();
Ethan Nicholas00543112018-07-31 09:44:36 -04001867 }
Ethan Nicholas762466e2017-06-29 10:03:38 -04001868 return result;
1869}
Brian Osmanfb32ddf2019-06-18 10:14:20 -04001870#endif
1871
Ethan Nicholas0e9401d2019-03-21 11:05:37 -04001872std::unique_ptr<ByteCode> Compiler::toByteCode(Program& program) {
Mike Klein853d4ed2020-08-20 00:41:00 +00001873#if defined(SK_ENABLE_SKSL_INTERPRETER)
Brian Osman808f0212020-01-21 15:36:47 -05001874 fSource = program.fSource.get();
Ethan Nicholas0e9401d2019-03-21 11:05:37 -04001875 std::unique_ptr<ByteCode> result(new ByteCode());
Brian Osmanb08cc022020-04-02 11:38:40 -04001876 ByteCodeGenerator cg(fContext.get(), &program, this, result.get());
1877 bool success = cg.generateCode();
1878 fSource = nullptr;
1879 if (success) {
Ethan Nicholas0e9401d2019-03-21 11:05:37 -04001880 return result;
1881 }
Mike Klein853d4ed2020-08-20 00:41:00 +00001882#else
1883 ABORT("ByteCode interpreter not enabled");
1884#endif
Ethan Nicholas0e9401d2019-03-21 11:05:37 -04001885 return nullptr;
1886}
1887
Brian Osman401a0092020-09-10 14:47:24 -04001888const char* Compiler::OperatorName(Token::Kind op) {
1889 switch (op) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001890 case Token::Kind::TK_PLUS: return "+";
1891 case Token::Kind::TK_MINUS: return "-";
1892 case Token::Kind::TK_STAR: return "*";
1893 case Token::Kind::TK_SLASH: return "/";
1894 case Token::Kind::TK_PERCENT: return "%";
1895 case Token::Kind::TK_SHL: return "<<";
1896 case Token::Kind::TK_SHR: return ">>";
1897 case Token::Kind::TK_LOGICALNOT: return "!";
1898 case Token::Kind::TK_LOGICALAND: return "&&";
1899 case Token::Kind::TK_LOGICALOR: return "||";
1900 case Token::Kind::TK_LOGICALXOR: return "^^";
1901 case Token::Kind::TK_BITWISENOT: return "~";
1902 case Token::Kind::TK_BITWISEAND: return "&";
1903 case Token::Kind::TK_BITWISEOR: return "|";
1904 case Token::Kind::TK_BITWISEXOR: return "^";
1905 case Token::Kind::TK_EQ: return "=";
1906 case Token::Kind::TK_EQEQ: return "==";
1907 case Token::Kind::TK_NEQ: return "!=";
1908 case Token::Kind::TK_LT: return "<";
1909 case Token::Kind::TK_GT: return ">";
1910 case Token::Kind::TK_LTEQ: return "<=";
1911 case Token::Kind::TK_GTEQ: return ">=";
1912 case Token::Kind::TK_PLUSEQ: return "+=";
1913 case Token::Kind::TK_MINUSEQ: return "-=";
1914 case Token::Kind::TK_STAREQ: return "*=";
1915 case Token::Kind::TK_SLASHEQ: return "/=";
1916 case Token::Kind::TK_PERCENTEQ: return "%=";
1917 case Token::Kind::TK_SHLEQ: return "<<=";
1918 case Token::Kind::TK_SHREQ: return ">>=";
1919 case Token::Kind::TK_LOGICALANDEQ: return "&&=";
1920 case Token::Kind::TK_LOGICALOREQ: return "||=";
1921 case Token::Kind::TK_LOGICALXOREQ: return "^^=";
1922 case Token::Kind::TK_BITWISEANDEQ: return "&=";
1923 case Token::Kind::TK_BITWISEOREQ: return "|=";
1924 case Token::Kind::TK_BITWISEXOREQ: return "^=";
1925 case Token::Kind::TK_PLUSPLUS: return "++";
1926 case Token::Kind::TK_MINUSMINUS: return "--";
1927 case Token::Kind::TK_COMMA: return ",";
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001928 default:
Brian Osman401a0092020-09-10 14:47:24 -04001929 ABORT("unsupported operator: %d\n", (int) op);
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001930 }
1931}
1932
1933
1934bool Compiler::IsAssignment(Token::Kind op) {
1935 switch (op) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001936 case Token::Kind::TK_EQ: // fall through
1937 case Token::Kind::TK_PLUSEQ: // fall through
1938 case Token::Kind::TK_MINUSEQ: // fall through
1939 case Token::Kind::TK_STAREQ: // fall through
1940 case Token::Kind::TK_SLASHEQ: // fall through
1941 case Token::Kind::TK_PERCENTEQ: // fall through
1942 case Token::Kind::TK_SHLEQ: // fall through
1943 case Token::Kind::TK_SHREQ: // fall through
1944 case Token::Kind::TK_BITWISEOREQ: // fall through
1945 case Token::Kind::TK_BITWISEXOREQ: // fall through
1946 case Token::Kind::TK_BITWISEANDEQ: // fall through
1947 case Token::Kind::TK_LOGICALOREQ: // fall through
1948 case Token::Kind::TK_LOGICALXOREQ: // fall through
1949 case Token::Kind::TK_LOGICALANDEQ:
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001950 return true;
1951 default:
1952 return false;
1953 }
1954}
1955
Brian Osman401a0092020-09-10 14:47:24 -04001956Token::Kind Compiler::RemoveAssignment(Token::Kind op) {
1957 switch (op) {
1958 case Token::Kind::TK_PLUSEQ: return Token::Kind::TK_PLUS;
1959 case Token::Kind::TK_MINUSEQ: return Token::Kind::TK_MINUS;
1960 case Token::Kind::TK_STAREQ: return Token::Kind::TK_STAR;
1961 case Token::Kind::TK_SLASHEQ: return Token::Kind::TK_SLASH;
1962 case Token::Kind::TK_PERCENTEQ: return Token::Kind::TK_PERCENT;
1963 case Token::Kind::TK_SHLEQ: return Token::Kind::TK_SHL;
1964 case Token::Kind::TK_SHREQ: return Token::Kind::TK_SHR;
1965 case Token::Kind::TK_BITWISEOREQ: return Token::Kind::TK_BITWISEOR;
1966 case Token::Kind::TK_BITWISEXOREQ: return Token::Kind::TK_BITWISEXOR;
1967 case Token::Kind::TK_BITWISEANDEQ: return Token::Kind::TK_BITWISEAND;
1968 case Token::Kind::TK_LOGICALOREQ: return Token::Kind::TK_LOGICALOR;
1969 case Token::Kind::TK_LOGICALXOREQ: return Token::Kind::TK_LOGICALXOR;
1970 case Token::Kind::TK_LOGICALANDEQ: return Token::Kind::TK_LOGICALAND;
1971 default: return op;
1972 }
1973}
1974
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001975Position Compiler::position(int offset) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001976 SkASSERT(fSource);
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001977 int line = 1;
1978 int column = 1;
1979 for (int i = 0; i < offset; i++) {
1980 if ((*fSource)[i] == '\n') {
1981 ++line;
1982 column = 1;
1983 }
1984 else {
1985 ++column;
1986 }
1987 }
1988 return Position(line, column);
1989}
1990
1991void Compiler::error(int offset, String msg) {
ethannicholasb3058bd2016-07-01 08:22:01 -07001992 fErrorCount++;
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001993 Position pos = this->position(offset);
1994 fErrorText += "error: " + to_string(pos.fLine) + ": " + msg.c_str() + "\n";
ethannicholasb3058bd2016-07-01 08:22:01 -07001995}
1996
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001997String Compiler::errorText() {
Ethan Nicholas00543112018-07-31 09:44:36 -04001998 this->writeErrorCount();
1999 fErrorCount = 0;
Ethan Nicholas0df1b042017-03-31 13:56:23 -04002000 String result = fErrorText;
ethannicholasb3058bd2016-07-01 08:22:01 -07002001 return result;
2002}
2003
2004void Compiler::writeErrorCount() {
2005 if (fErrorCount) {
2006 fErrorText += to_string(fErrorCount) + " error";
2007 if (fErrorCount > 1) {
2008 fErrorText += "s";
2009 }
2010 fErrorText += "\n";
2011 }
2012}
2013
John Stilesa6841be2020-08-06 14:11:56 -04002014} // namespace SkSL