1 // Copyright 2021 The Tint Authors.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 #include "src/transform/fold_trivial_single_use_lets.h"
16
17 #include "src/program_builder.h"
18 #include "src/sem/block_statement.h"
19 #include "src/sem/function.h"
20 #include "src/sem/statement.h"
21 #include "src/sem/variable.h"
22 #include "src/utils/scoped_assignment.h"
23
24 TINT_INSTANTIATE_TYPEINFO(tint::transform::FoldTrivialSingleUseLets);
25
26 namespace tint {
27 namespace transform {
28 namespace {
29
AsTrivialLetDecl(const ast::Statement * stmt)30 const ast::VariableDeclStatement* AsTrivialLetDecl(const ast::Statement* stmt) {
31 auto* var_decl = stmt->As<ast::VariableDeclStatement>();
32 if (!var_decl) {
33 return nullptr;
34 }
35 auto* var = var_decl->variable;
36 if (!var->is_const) {
37 return nullptr;
38 }
39 auto* ctor = var->constructor;
40 if (!IsAnyOf<ast::IdentifierExpression, ast::LiteralExpression>(ctor)) {
41 return nullptr;
42 }
43 return var_decl;
44 }
45
46 } // namespace
47
48 FoldTrivialSingleUseLets::FoldTrivialSingleUseLets() = default;
49
50 FoldTrivialSingleUseLets::~FoldTrivialSingleUseLets() = default;
51
Run(CloneContext & ctx,const DataMap &,DataMap &)52 void FoldTrivialSingleUseLets::Run(CloneContext& ctx,
53 const DataMap&,
54 DataMap&) {
55 for (auto* node : ctx.src->ASTNodes().Objects()) {
56 if (auto* block = node->As<ast::BlockStatement>()) {
57 auto& stmts = block->statements;
58 for (size_t stmt_idx = 0; stmt_idx < stmts.size(); stmt_idx++) {
59 auto* stmt = stmts[stmt_idx];
60 if (auto* let_decl = AsTrivialLetDecl(stmt)) {
61 auto* let = let_decl->variable;
62 auto* sem_let = ctx.src->Sem().Get(let);
63 auto& users = sem_let->Users();
64 if (users.size() != 1) {
65 continue; // Does not have a single user.
66 }
67
68 auto* user = users[0];
69 auto* user_stmt = user->Stmt()->Declaration();
70
71 for (size_t i = stmt_idx; i < stmts.size(); i++) {
72 if (user_stmt == stmts[i]) {
73 auto* user_expr = user->Declaration();
74 ctx.Remove(stmts, let_decl);
75 ctx.Replace(user_expr, ctx.Clone(let->constructor));
76 }
77 if (!AsTrivialLetDecl(stmts[i])) {
78 // Stop if we hit a statement that isn't the single use of the
79 // let, and isn't a let itself.
80 break;
81 }
82 }
83 }
84 }
85 }
86 }
87
88 ctx.Clone();
89 }
90
91 } // namespace transform
92 } // namespace tint
93