[spirv-writer] Add relational add

This CL adds the relational add expression to the spirv writer.

Bug: tint:5
Change-Id: Ideed225c63e60f53a019b79803809f8e973299c6
Reviewed-on: https://dawn-review.googlesource.com/c/tint/+/18605
Reviewed-by: David Neto <dneto@google.com>
diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt
index 470df63..3426625 100644
--- a/src/CMakeLists.txt
+++ b/src/CMakeLists.txt
@@ -423,6 +423,7 @@
   list(APPEND TINT_TEST_SRCS
     writer/spirv/binary_writer_test.cc
     writer/spirv/builder_assign_test.cc
+    writer/spirv/builder_binary_expression_test.cc
     writer/spirv/builder_constructor_expression_test.cc
     writer/spirv/builder_entry_point_test.cc
     writer/spirv/builder_function_test.cc
diff --git a/src/reader/spirv/function_decl_test.cc b/src/reader/spirv/function_decl_test.cc
index 2e2c35c..75cc74f 100644
--- a/src/reader/spirv/function_decl_test.cc
+++ b/src/reader/spirv/function_decl_test.cc
@@ -12,12 +12,11 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
-#include "src/reader/spirv/function.h"
-
 #include <string>
 #include <vector>
 
 #include "gmock/gmock.h"
+#include "src/reader/spirv/function.h"
 #include "src/reader/spirv/parser_impl.h"
 #include "src/reader/spirv/parser_impl_test_helper.h"
 #include "src/reader/spirv/spirv_tools_helpers_test.h"
diff --git a/src/writer/spirv/builder.cc b/src/writer/spirv/builder.cc
index 53ddaf7..83277a6 100644
--- a/src/writer/spirv/builder.cc
+++ b/src/writer/spirv/builder.cc
@@ -18,6 +18,7 @@
 
 #include "spirv/unified1/spirv.h"
 #include "src/ast/assignment_statement.h"
+#include "src/ast/binary_expression.h"
 #include "src/ast/binding_decoration.h"
 #include "src/ast/bool_literal.h"
 #include "src/ast/builtin_decoration.h"
@@ -163,8 +164,7 @@
     return false;
   }
 
-  push_function_inst(spv::Op::OpStore,
-                     {Operand::Int(lhs_id), Operand::Int(rhs_id)});
+  GenerateStore(lhs_id, rhs_id);
   return true;
 }
 
@@ -193,12 +193,15 @@
 }
 
 uint32_t Builder::GenerateExpression(ast::Expression* expr) {
-  if (expr->IsIdentifier()) {
-    return GenerateIdentifierExpression(expr->AsIdentifier());
+  if (expr->IsBinary()) {
+    return GenerateBinaryExpression(expr->AsBinary());
   }
   if (expr->IsConstructor()) {
     return GenerateConstructorExpression(expr->AsConstructor(), false);
   }
+  if (expr->IsIdentifier()) {
+    return GenerateIdentifierExpression(expr->AsIdentifier());
+  }
 
   error_ = "unknown expression type";
   return 0;
@@ -301,8 +304,7 @@
   push_function_var(
       {Operand::Int(type_id), result, Operand::Int(ConvertStorageClass(sc))});
   if (var->has_constructor()) {
-    push_function_inst(spv::Op::OpStore,
-                       {Operand::Int(var_id), Operand::Int(init_id)});
+    GenerateStore(var_id, init_id);
   }
 
   scope_stack_.set(var->name(), var_id);
@@ -310,6 +312,10 @@
   return true;
 }
 
+void Builder::GenerateStore(uint32_t to, uint32_t from) {
+  push_function_inst(spv::Op::OpStore, {Operand::Int(to), Operand::Int(from)});
+}
+
 bool Builder::GenerateGlobalVariable(ast::Variable* var) {
   uint32_t init_id = 0;
   if (var->has_constructor()) {
@@ -508,6 +514,41 @@
   return result_id;
 }
 
+uint32_t Builder::GenerateBinaryExpression(ast::BinaryExpression* expr) {
+  if (expr->IsAdd()) {
+    auto lhs_id = GenerateExpression(expr->lhs());
+    if (lhs_id == 0) {
+      return 0;
+    }
+    auto rhs_id = GenerateExpression(expr->rhs());
+    if (rhs_id == 0) {
+      return 0;
+    }
+
+    auto result = result_op();
+    auto result_id = result.to_i();
+
+    auto expr_type = expr->result_type();
+    auto type_id = GenerateTypeIfNeeded(expr_type);
+    if (type_id == 0) {
+      return 0;
+    }
+
+    // This handles int and float and the vectors of those types. Other types
+    // should have been rejected by validation.
+    spv::Op op = spv::Op::OpIAdd;
+    if (expr_type->IsF32() ||
+        (expr_type->IsVector() && expr_type->AsVector()->type()->IsF32())) {
+      op = spv::Op::OpFAdd;
+    }
+    push_function_inst(op, {Operand::Int(type_id), result, Operand::Int(lhs_id),
+                            Operand::Int(rhs_id)});
+
+    return result_id;
+  }
+  return 0;
+}
+
 bool Builder::GenerateReturnStatement(ast::ReturnStatement* stmt) {
   if (stmt->has_value()) {
     auto val_id = GenerateExpression(stmt->value());
@@ -542,6 +583,11 @@
 }
 
 uint32_t Builder::GenerateTypeIfNeeded(ast::type::Type* type) {
+  if (type == nullptr) {
+    error_ = "attempting to generate type from null type";
+    return 0;
+  }
+
   if (type->IsAlias()) {
     return GenerateTypeIfNeeded(type->AsAlias()->type());
   }
diff --git a/src/writer/spirv/builder.h b/src/writer/spirv/builder.h
index 405505c..ad1805b 100644
--- a/src/writer/spirv/builder.h
+++ b/src/writer/spirv/builder.h
@@ -189,6 +189,10 @@
   /// @param lit the literal to generate
   /// @returns the ID on success or 0 on failure
   uint32_t GenerateLiteralIfNeeded(ast::Literal* lit);
+  /// Generates a binary expression
+  /// @param expr the expression to generate
+  /// @returns the expression ID on success or 0 otherwise
+  uint32_t GenerateBinaryExpression(ast::BinaryExpression* expr);
   /// Generates a return statement
   /// @param stmt the statement to generate
   /// @returns true on success, false otherwise
@@ -197,6 +201,10 @@
   /// @param stmt the statement to generate
   /// @returns true if the statement was generated
   bool GenerateStatement(ast::Statement* stmt);
+  /// Geneates an OpStore
+  /// @param to the ID to store too
+  /// @param from the ID to store from
+  void GenerateStore(uint32_t to, uint32_t from);
   /// Generates a type if not already created
   /// @param type the type to create
   /// @returns the ID to use for the given type. Returns 0 on unknown type.
diff --git a/src/writer/spirv/builder_binary_expression_test.cc b/src/writer/spirv/builder_binary_expression_test.cc
new file mode 100644
index 0000000..f7a79f6
--- /dev/null
+++ b/src/writer/spirv/builder_binary_expression_test.cc
@@ -0,0 +1,183 @@
+// Copyright 2020 The Tint Authors.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//     http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include <memory>
+
+#include "gtest/gtest.h"
+#include "src/ast/binary_expression.h"
+#include "src/ast/type_constructor_expression.h"
+#include "src/ast/float_literal.h"
+#include "src/ast/int_literal.h"
+#include "src/ast/scalar_constructor_expression.h"
+#include "src/ast/type/f32_type.h"
+#include "src/ast/type/i32_type.h"
+#include "src/ast/type/vector_type.h"
+#include "src/context.h"
+#include "src/type_determiner.h"
+#include "src/writer/spirv/builder.h"
+#include "src/writer/spirv/spv_dump.h"
+
+namespace tint {
+namespace writer {
+namespace spirv {
+namespace {
+
+using BuilderTest = testing::Test;
+
+TEST_F(BuilderTest, Binary_Add_Integer) {
+  ast::type::I32Type i32;
+
+  auto lhs = std::make_unique<ast::ScalarConstructorExpression>(
+      std::make_unique<ast::IntLiteral>(&i32, 3));
+  auto rhs = std::make_unique<ast::ScalarConstructorExpression>(
+      std::make_unique<ast::IntLiteral>(&i32, 4));
+
+  ast::BinaryExpression expr(ast::BinaryOp::kAdd, std::move(lhs),
+                             std::move(rhs));
+
+  Context ctx;
+  TypeDeterminer td(&ctx);
+  ASSERT_TRUE(td.DetermineResultType(&expr)) << td.error();
+
+  Builder b;
+  b.push_function(Function{});
+
+  ASSERT_EQ(b.GenerateBinaryExpression(&expr), 4) << b.error();
+  EXPECT_EQ(DumpInstructions(b.types()), R"(%1 = OpTypeInt 32 1
+%2 = OpConstant %1 3
+%3 = OpConstant %1 4
+)");
+  EXPECT_EQ(DumpInstructions(b.functions()[0].instructions()),
+            R"(%4 = OpIAdd %1 %2 %3
+)");
+}
+
+TEST_F(BuilderTest, Binary_Add_Integer_Vectors) {
+  ast::type::I32Type i32;
+  ast::type::VectorType vec3(&i32, 3);
+
+  ast::ExpressionList vals;
+  vals.push_back(std::make_unique<ast::ScalarConstructorExpression>(
+        std::make_unique<ast::IntLiteral>(&i32, 1)));
+  vals.push_back(std::make_unique<ast::ScalarConstructorExpression>(
+        std::make_unique<ast::IntLiteral>(&i32, 1)));
+  vals.push_back(std::make_unique<ast::ScalarConstructorExpression>(
+        std::make_unique<ast::IntLiteral>(&i32, 1)));
+  auto lhs = std::make_unique<ast::TypeConstructorExpression>(&vec3, std::move(vals));
+
+  vals.push_back(std::make_unique<ast::ScalarConstructorExpression>(
+        std::make_unique<ast::IntLiteral>(&i32, 1)));
+  vals.push_back(std::make_unique<ast::ScalarConstructorExpression>(
+        std::make_unique<ast::IntLiteral>(&i32, 1)));
+  vals.push_back(std::make_unique<ast::ScalarConstructorExpression>(
+        std::make_unique<ast::IntLiteral>(&i32, 1)));
+  auto rhs = std::make_unique<ast::TypeConstructorExpression>(&vec3, std::move(vals));
+
+  Context ctx;
+  TypeDeterminer td(&ctx);
+
+  ast::BinaryExpression expr(
+      ast::BinaryOp::kAdd, std::move(lhs), std::move(rhs));
+
+  ASSERT_TRUE(td.DetermineResultType(&expr)) << td.error();
+
+  Builder b;
+  b.push_function(Function{});
+
+  ASSERT_EQ(b.GenerateBinaryExpression(&expr), 5) << b.error();
+  EXPECT_EQ(DumpInstructions(b.types()), R"(%2 = OpTypeInt 32 1
+%1 = OpTypeVector %2 3
+%3 = OpConstant %2 1
+%4 = OpConstantComposite %1 %3 %3 %3
+)");
+  EXPECT_EQ(DumpInstructions(b.functions()[0].instructions()),
+            R"(%5 = OpIAdd %1 %4 %4
+)");
+}
+
+TEST_F(BuilderTest, Binary_Add_Float) {
+  ast::type::F32Type f32;
+
+  auto lhs = std::make_unique<ast::ScalarConstructorExpression>(
+      std::make_unique<ast::FloatLiteral>(&f32, 3.2f));
+  auto rhs = std::make_unique<ast::ScalarConstructorExpression>(
+      std::make_unique<ast::FloatLiteral>(&f32, 4.5f));
+
+  ast::BinaryExpression expr(ast::BinaryOp::kAdd, std::move(lhs),
+                             std::move(rhs));
+
+  Context ctx;
+  TypeDeterminer td(&ctx);
+  ASSERT_TRUE(td.DetermineResultType(&expr)) << td.error();
+
+  Builder b;
+  b.push_function(Function{});
+
+  ASSERT_EQ(b.GenerateBinaryExpression(&expr), 4) << b.error();
+  EXPECT_EQ(DumpInstructions(b.types()), R"(%1 = OpTypeFloat 32
+%2 = OpConstant %1 3.20000005
+%3 = OpConstant %1 4.5
+)");
+  EXPECT_EQ(DumpInstructions(b.functions()[0].instructions()),
+            R"(%4 = OpFAdd %1 %2 %3
+)");
+}
+
+TEST_F(BuilderTest, Binary_Add_Float_Vectors) {
+  ast::type::F32Type f32;
+  ast::type::VectorType vec3(&f32, 3);
+
+  ast::ExpressionList vals;
+  vals.push_back(std::make_unique<ast::ScalarConstructorExpression>(
+        std::make_unique<ast::FloatLiteral>(&f32, 1.f)));
+  vals.push_back(std::make_unique<ast::ScalarConstructorExpression>(
+        std::make_unique<ast::FloatLiteral>(&f32, 1.f)));
+  vals.push_back(std::make_unique<ast::ScalarConstructorExpression>(
+        std::make_unique<ast::FloatLiteral>(&f32, 1.f)));
+  auto lhs = std::make_unique<ast::TypeConstructorExpression>(&vec3, std::move(vals));
+
+  vals.push_back(std::make_unique<ast::ScalarConstructorExpression>(
+        std::make_unique<ast::FloatLiteral>(&f32, 1.f)));
+  vals.push_back(std::make_unique<ast::ScalarConstructorExpression>(
+        std::make_unique<ast::FloatLiteral>(&f32, 1.f)));
+  vals.push_back(std::make_unique<ast::ScalarConstructorExpression>(
+        std::make_unique<ast::FloatLiteral>(&f32, 1.f)));
+  auto rhs = std::make_unique<ast::TypeConstructorExpression>(&vec3, std::move(vals));
+
+  Context ctx;
+  TypeDeterminer td(&ctx);
+
+  ast::BinaryExpression expr(
+      ast::BinaryOp::kAdd, std::move(lhs), std::move(rhs));
+
+  ASSERT_TRUE(td.DetermineResultType(&expr)) << td.error();
+
+  Builder b;
+  b.push_function(Function{});
+
+  ASSERT_EQ(b.GenerateBinaryExpression(&expr), 5) << b.error();
+  EXPECT_EQ(DumpInstructions(b.types()), R"(%2 = OpTypeFloat 32
+%1 = OpTypeVector %2 3
+%3 = OpConstant %2 1
+%4 = OpConstantComposite %1 %3 %3 %3
+)");
+  EXPECT_EQ(DumpInstructions(b.functions()[0].instructions()),
+            R"(%5 = OpFAdd %1 %4 %4
+)");
+}
+
+}  // namespace
+}  // namespace spirv
+}  // namespace writer
+}  // namespace tint