[spirv-writer] Simple if statements.

This CL adds the code to generate simple if statements.

Bug: tint:5
Change-Id: Ied42ad8b3632d7926ac646d1aa21e190a7a2c07e
Reviewed-on: https://dawn-review.googlesource.com/c/tint/+/19411
Reviewed-by: David Neto <dneto@google.com>
diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt
index 83cee3e..609542c 100644
--- a/src/CMakeLists.txt
+++ b/src/CMakeLists.txt
@@ -427,6 +427,7 @@
     writer/spirv/builder_function_variable_test.cc
     writer/spirv/builder_global_variable_test.cc
     writer/spirv/builder_ident_expression_test.cc
+    writer/spirv/builder_if_test.cc
     writer/spirv/builder_literal_test.cc
     writer/spirv/builder_return_test.cc
     writer/spirv/builder_test.cc
diff --git a/src/ast/if_statement.h b/src/ast/if_statement.h
index 3e57f17..f173de4 100644
--- a/src/ast/if_statement.h
+++ b/src/ast/if_statement.h
@@ -66,6 +66,8 @@
   }
   /// @returns the else statements
   const ElseStatementList& else_statements() const { return else_statements_; }
+  /// @returns true if there are else statements
+  bool has_else_statements() const { return !else_statements_.empty(); }
 
   /// @returns true if this is a if statement
   bool IsIf() const override;
diff --git a/src/writer/spirv/builder.cc b/src/writer/spirv/builder.cc
index dac803a..566b8c7 100644
--- a/src/writer/spirv/builder.cc
+++ b/src/writer/spirv/builder.cc
@@ -26,6 +26,7 @@
 #include "src/ast/decorated_variable.h"
 #include "src/ast/float_literal.h"
 #include "src/ast/identifier_expression.h"
+#include "src/ast/if_statement.h"
 #include "src/ast/int_literal.h"
 #include "src/ast/location_decoration.h"
 #include "src/ast/return_statement.h"
@@ -628,6 +629,56 @@
   return result_id;
 }
 
+bool Builder::GenerateIfStatement(ast::IfStatement* stmt) {
+  auto cond_id = GenerateExpression(stmt->condition());
+  if (cond_id == 0) {
+    return false;
+  }
+
+  auto merge_block = result_op();
+  auto merge_block_id = merge_block.to_i();
+
+  push_function_inst(spv::Op::OpSelectionMerge,
+                     {Operand::Int(merge_block_id),
+                      Operand::Int(SpvSelectionControlMaskNone)});
+
+  auto true_block = result_op();
+  auto true_block_id = true_block.to_i();
+
+  // if there are no else statements we branch on false to the merge block
+  // otherwise we branch to the false block
+  auto false_block_id =
+      stmt->has_else_statements() ? next_id() : merge_block_id;
+
+  push_function_inst(spv::Op::OpBranchConditional,
+                     {Operand::Int(cond_id), Operand::Int(true_block_id),
+                      Operand::Int(false_block_id)});
+
+  // Output true block
+  push_function_inst(spv::Op::OpLabel, {true_block});
+  for (const auto& inst : stmt->body()) {
+    if (!GenerateStatement(inst.get())) {
+      return 0;
+    }
+  }
+
+  // TODO(dsinclair): The branch should be optional based on how the
+  // StatementList ended ...
+
+  push_function_inst(spv::Op::OpBranch, {Operand::Int(merge_block_id)});
+
+  if (false_block_id != merge_block_id) {
+    push_function_inst(spv::Op::OpLabel, {Operand::Int(false_block_id)});
+
+    // TODO(dsinclair): Output else statements, pass in merge_block_id?
+  }
+
+  // Output the merge block
+  push_function_inst(spv::Op::OpLabel, {merge_block});
+
+  return true;
+}
+
 bool Builder::GenerateReturnStatement(ast::ReturnStatement* stmt) {
   if (stmt->has_value()) {
     auto val_id = GenerateExpression(stmt->value());
@@ -646,6 +697,9 @@
   if (stmt->IsAssign()) {
     return GenerateAssignStatement(stmt->AsAssign());
   }
+  if (stmt->IsIf()) {
+    return GenerateIfStatement(stmt->AsIf());
+  }
   if (stmt->IsReturn()) {
     return GenerateReturnStatement(stmt->AsReturn());
   }
diff --git a/src/writer/spirv/builder.h b/src/writer/spirv/builder.h
index fa765ab..d2981a1 100644
--- a/src/writer/spirv/builder.h
+++ b/src/writer/spirv/builder.h
@@ -180,6 +180,10 @@
   /// @param expr the expresssion to generate
   /// @returns the id of the expression or 0 on failure
   uint32_t GenerateIdentifierExpression(ast::IdentifierExpression* expr);
+  /// Generates an if statement
+  /// @param stmt the statement to generate
+  /// @returns true on success
+  bool GenerateIfStatement(ast::IfStatement* stmt);
   /// Generates an import instruction
   /// @param imp the import
   void GenerateImport(ast::Import* imp);
diff --git a/src/writer/spirv/builder_if_test.cc b/src/writer/spirv/builder_if_test.cc
new file mode 100644
index 0000000..1be836a
--- /dev/null
+++ b/src/writer/spirv/builder_if_test.cc
@@ -0,0 +1,129 @@
+// 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/assignment_statement.h"
+#include "src/ast/bool_literal.h"
+#include "src/ast/identifier_expression.h"
+#include "src/ast/if_statement.h"
+#include "src/ast/int_literal.h"
+#include "src/ast/scalar_constructor_expression.h"
+#include "src/ast/type/bool_type.h"
+#include "src/ast/type/i32_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, If_Empty) {
+  ast::type::BoolType bool_type;
+
+  auto cond = std::make_unique<ast::ScalarConstructorExpression>(
+      std::make_unique<ast::BoolLiteral>(&bool_type, true));
+
+  ast::IfStatement expr(std::move(cond), ast::StatementList{});
+
+  Context ctx;
+  TypeDeterminer td(&ctx);
+  ASSERT_TRUE(td.DetermineResultType(&expr)) << td.error();
+
+  Builder b;
+  b.push_function(Function{});
+
+  EXPECT_TRUE(b.GenerateIfStatement(&expr)) << b.error();
+  EXPECT_EQ(DumpInstructions(b.types()), R"(%1 = OpTypeBool
+%2 = OpConstantTrue %1
+)");
+  EXPECT_EQ(DumpInstructions(b.functions()[0].instructions()),
+            R"(OpSelectionMerge %3 None
+OpBranchConditional %2 %4 %3
+%4 = OpLabel
+OpBranch %3
+%3 = OpLabel
+)");
+}
+
+TEST_F(BuilderTest, If_WithStatements) {
+  ast::type::BoolType bool_type;
+  ast::type::I32Type i32;
+
+  auto var =
+      std::make_unique<ast::Variable>("v", ast::StorageClass::kPrivate, &i32);
+
+  ast::StatementList body;
+  body.push_back(std::make_unique<ast::AssignmentStatement>(
+      std::make_unique<ast::IdentifierExpression>("v"),
+      std::make_unique<ast::ScalarConstructorExpression>(
+          std::make_unique<ast::IntLiteral>(&i32, 2))));
+
+  auto cond = std::make_unique<ast::ScalarConstructorExpression>(
+      std::make_unique<ast::BoolLiteral>(&bool_type, true));
+
+  ast::IfStatement expr(std::move(cond), std::move(body));
+
+  Context ctx;
+  TypeDeterminer td(&ctx);
+  td.RegisterVariableForTesting(var.get());
+
+  ASSERT_TRUE(td.DetermineResultType(&expr)) << td.error();
+
+  Builder b;
+  b.push_function(Function{});
+  ASSERT_TRUE(b.GenerateGlobalVariable(var.get())) << b.error();
+
+  EXPECT_TRUE(b.GenerateIfStatement(&expr)) << b.error();
+  EXPECT_EQ(DumpInstructions(b.types()), R"(%3 = OpTypeInt 32 1
+%2 = OpTypePointer Private %3
+%1 = OpVariable %2 Private
+%4 = OpTypeBool
+%5 = OpConstantTrue %4
+%8 = OpConstant %3 2
+)");
+  EXPECT_EQ(DumpInstructions(b.functions()[0].instructions()),
+            R"(OpSelectionMerge %6 None
+OpBranchConditional %5 %7 %6
+%7 = OpLabel
+OpStore %1 %8
+OpBranch %6
+%6 = OpLabel
+)");
+}
+
+TEST_F(BuilderTest, DISABLED_If_WithStatements_Returns) {
+  // if (a) { return; }
+}
+
+TEST_F(BuilderTest, DISABLED_If_WithElse) {}
+
+TEST_F(BuilderTest, DISABLED_If_WithElseIf) {}
+
+TEST_F(BuilderTest, DISABLED_If_WithMultiple) {}
+
+TEST_F(BuilderTest, DISABLED_If_WithBreak) {}
+
+TEST_F(BuilderTest, DISABLED_If_WithContinue) {}
+
+}  // namespace
+}  // namespace spirv
+}  // namespace writer
+}  // namespace tint