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/vectorize_scalar_matrix_constructors.h"
16
17 #include <utility>
18
19 #include "src/program_builder.h"
20 #include "src/sem/call.h"
21 #include "src/sem/expression.h"
22 #include "src/sem/type_constructor.h"
23
24 TINT_INSTANTIATE_TYPEINFO(tint::transform::VectorizeScalarMatrixConstructors);
25
26 namespace tint {
27 namespace transform {
28
29 VectorizeScalarMatrixConstructors::VectorizeScalarMatrixConstructors() =
30 default;
31
32 VectorizeScalarMatrixConstructors::~VectorizeScalarMatrixConstructors() =
33 default;
34
Run(CloneContext & ctx,const DataMap &,DataMap &)35 void VectorizeScalarMatrixConstructors::Run(CloneContext& ctx,
36 const DataMap&,
37 DataMap&) {
38 ctx.ReplaceAll(
39 [&](const ast::CallExpression* expr) -> const ast::CallExpression* {
40 auto* call = ctx.src->Sem().Get(expr);
41 auto* ty_ctor = call->Target()->As<sem::TypeConstructor>();
42 if (!ty_ctor) {
43 return nullptr;
44 }
45 // Check if this is a matrix constructor with scalar arguments.
46 auto* mat_type = call->Type()->As<sem::Matrix>();
47 if (!mat_type) {
48 return nullptr;
49 }
50
51 auto& args = call->Arguments();
52 if (args.size() == 0) {
53 return nullptr;
54 }
55 if (!args[0]->Type()->is_scalar()) {
56 return nullptr;
57 }
58
59 // Build a list of vector expressions for each column.
60 ast::ExpressionList columns;
61 for (uint32_t c = 0; c < mat_type->columns(); c++) {
62 // Build a list of scalar expressions for each value in the column.
63 ast::ExpressionList row_values;
64 for (uint32_t r = 0; r < mat_type->rows(); r++) {
65 row_values.push_back(
66 ctx.Clone(args[c * mat_type->rows() + r]->Declaration()));
67 }
68
69 // Construct the column vector.
70 auto* col = ctx.dst->vec(CreateASTTypeFor(ctx, mat_type->type()),
71 mat_type->rows(), row_values);
72 columns.push_back(col);
73 }
74 return ctx.dst->Construct(CreateASTTypeFor(ctx, mat_type), columns);
75 });
76
77 ctx.Clone();
78 }
79
80 } // namespace transform
81 } // namespace tint
82