<commit_before>/*
 * Copyright © 2010 Intel Corporation
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice (including the next
 * paragraph) shall be included in all copies or substantial portions of the
 * Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 */

/**
 * \file ir_copy_propagation.cpp
 *
 * Moves usage of recently-copied variables to the previous copy of
 * the variable within basic blocks.
 *
 * This should reduce the number of MOV instructions in the generated
 * programs unless copy propagation is also done on the LIR, and may
 * help anyway by triggering other optimizations that live in the HIR.
 */

#include "ir.h"
#include "ir_visitor.h"
#include "ir_basic_block.h"
#include "ir_optimization.h"
#include "glsl_types.h"

class acp_entry : public exec_node
{
public:
   acp_entry(ir_variable *lhs, ir_variable *rhs)
   {
      assert(lhs);
      assert(rhs);
      this->lhs = lhs;
      this->rhs = rhs;
   }

   ir_variable *lhs;
   ir_variable *rhs;
};

class ir_copy_propagation_visitor : public ir_hierarchical_visitor {
public:
   ir_copy_propagation_visitor(exec_list *acp)
   {
      progress = false;
      in_lhs = false;
      this->acp = acp;
   }

   virtual ir_visitor_status visit(class ir_dereference_variable *);
   virtual ir_visitor_status visit_enter(class ir_loop *);
   virtual ir_visitor_status visit_enter(class ir_function_signature *);
   virtual ir_visitor_status visit_enter(class ir_function *);
   virtual ir_visitor_status visit_enter(class ir_assignment *);
   virtual ir_visitor_status visit_enter(class ir_call *);
   virtual ir_visitor_status visit_enter(class ir_if *);

   /** List of acp_entry */
   exec_list *acp;
   bool progress;

   /** Currently in the LHS of an assignment? */
   bool in_lhs;
};

ir_visitor_status
ir_copy_propagation_visitor::visit_enter(ir_loop *ir)
{
   (void)ir;
   return visit_continue_with_parent;
}

ir_visitor_status
ir_copy_propagation_visitor::visit_enter(ir_function_signature *ir)
{
   (void)ir;
   return visit_continue_with_parent;
}

ir_visitor_status
ir_copy_propagation_visitor::visit_enter(ir_assignment *ir)
{
   (void) ir;
   this->in_lhs = true;
   return visit_continue;
}

ir_visitor_status
ir_copy_propagation_visitor::visit_enter(ir_function *ir)
{
   (void) ir;
   return visit_continue_with_parent;
}

/**
 * Replaces dereferences of ACP RHS variables with ACP LHS variables.
 *
 * This is where the actual copy propagation occurs.  Note that the
 * rewriting of ir_dereference means that the ir_dereference instance
 * must not be shared by multiple IR operations!
 */
ir_visitor_status
ir_copy_propagation_visitor::visit(ir_dereference_variable *ir)
{
   /* Ignores the LHS.  Don't want to rewrite the LHS to point at some
    * other storage!
    */
   if (this->in_lhs) {
      this->in_lhs = false;
      return visit_continue;
   }

   ir_variable *var = ir->variable_referenced();

   foreach_iter(exec_list_iterator, iter, *this->acp) {
      acp_entry *entry = (acp_entry *)iter.get();

      if (var == entry->lhs) {
	 ir->var = entry->rhs;
	 this->progress = true;
	 break;
      }
   }

   return visit_continue;
}

ir_visitor_status
ir_copy_propagation_visitor::visit_enter(ir_call *ir)
{
   (void)ir;

   /* Note, if we were to do copy propagation to parameters of calls, we'd
    * have to be careful about out params.
    */
   return visit_continue_with_parent;
}

ir_visitor_status
ir_copy_propagation_visitor::visit_enter(ir_if *ir)
{
   ir->condition->accept(this);

   /* Do not traverse into the body of the if-statement since that is a
    * different basic block.
    */
   return visit_continue_with_parent;
}

static bool
propagate_copies(ir_instruction *ir, exec_list *acp)
{
   ir_copy_propagation_visitor v(acp);

   ir->accept(&v);

   return v.progress;
}

static void
kill_invalidated_copies(ir_assignment *ir, exec_list *acp)
{
   ir_variable *var = ir->lhs->variable_referenced();
   assert(var != NULL);

   foreach_iter(exec_list_iterator, iter, *acp) {
      acp_entry *entry = (acp_entry *)iter.get();

      if (entry->lhs == var || entry->rhs == var) {
	 entry->remove();
      }
   }
}

/**
 * Adds an entry to the available copy list if it's a plain assignment
 * of a variable to a variable.
 */
static void
add_copy(ir_assignment *ir, exec_list *acp)
{
   void *ctx = talloc_parent(ir);
   acp_entry *entry;

   if (ir->condition) {
      ir_constant *condition = ir->condition->as_constant();
      if (!condition || !condition->value.b[0])
	 return;
   }

   ir_variable *lhs_var = ir->lhs->whole_variable_referenced();
   ir_variable *rhs_var = ir->rhs->whole_variable_referenced();

   if ((lhs_var != NULL) && (rhs_var != NULL)) {
      entry = new(ctx) acp_entry(lhs_var, rhs_var);
      acp->push_tail(entry);
   }
}

static void
copy_propagation_basic_block(ir_instruction *first,
			     ir_instruction *last,
			     void *data)
{
   ir_instruction *ir;
   /* List of avaialble_copy */
   exec_list acp;
   bool *out_progress = (bool *)data;
   bool progress = false;

   for (ir = first;; ir = (ir_instruction *)ir->next) {
      ir_assignment *ir_assign = ir->as_assignment();

      progress = propagate_copies(ir, &acp) || progress;

      if (ir_assign) {
	 kill_invalidated_copies(ir_assign, &acp);

	 add_copy(ir_assign, &acp);
      }
      if (ir == last)
	 break;
   }
   *out_progress = progress;
}

/**
 * Does a copy propagation pass on the code present in the instruction stream.
 */
bool
do_copy_propagation(exec_list *instructions)
{
   bool progress = false;

   call_for_basic_blocks(instructions, copy_propagation_basic_block, &progress);

   return progress;
}
<commit_msg>Use a more sensible context in copy propagation.<commit_after>/*
 * Copyright © 2010 Intel Corporation
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice (including the next
 * paragraph) shall be included in all copies or substantial portions of the
 * Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 */

/**
 * \file ir_copy_propagation.cpp
 *
 * Moves usage of recently-copied variables to the previous copy of
 * the variable within basic blocks.
 *
 * This should reduce the number of MOV instructions in the generated
 * programs unless copy propagation is also done on the LIR, and may
 * help anyway by triggering other optimizations that live in the HIR.
 */

#include "ir.h"
#include "ir_visitor.h"
#include "ir_basic_block.h"
#include "ir_optimization.h"
#include "glsl_types.h"

class acp_entry : public exec_node
{
public:
   acp_entry(ir_variable *lhs, ir_variable *rhs)
   {
      assert(lhs);
      assert(rhs);
      this->lhs = lhs;
      this->rhs = rhs;
   }

   ir_variable *lhs;
   ir_variable *rhs;
};

class ir_copy_propagation_visitor : public ir_hierarchical_visitor {
public:
   ir_copy_propagation_visitor(exec_list *acp)
   {
      progress = false;
      in_lhs = false;
      this->acp = acp;
   }

   virtual ir_visitor_status visit(class ir_dereference_variable *);
   virtual ir_visitor_status visit_enter(class ir_loop *);
   virtual ir_visitor_status visit_enter(class ir_function_signature *);
   virtual ir_visitor_status visit_enter(class ir_function *);
   virtual ir_visitor_status visit_enter(class ir_assignment *);
   virtual ir_visitor_status visit_enter(class ir_call *);
   virtual ir_visitor_status visit_enter(class ir_if *);

   /** List of acp_entry */
   exec_list *acp;
   bool progress;

   /** Currently in the LHS of an assignment? */
   bool in_lhs;
};

ir_visitor_status
ir_copy_propagation_visitor::visit_enter(ir_loop *ir)
{
   (void)ir;
   return visit_continue_with_parent;
}

ir_visitor_status
ir_copy_propagation_visitor::visit_enter(ir_function_signature *ir)
{
   (void)ir;
   return visit_continue_with_parent;
}

ir_visitor_status
ir_copy_propagation_visitor::visit_enter(ir_assignment *ir)
{
   (void) ir;
   this->in_lhs = true;
   return visit_continue;
}

ir_visitor_status
ir_copy_propagation_visitor::visit_enter(ir_function *ir)
{
   (void) ir;
   return visit_continue_with_parent;
}

/**
 * Replaces dereferences of ACP RHS variables with ACP LHS variables.
 *
 * This is where the actual copy propagation occurs.  Note that the
 * rewriting of ir_dereference means that the ir_dereference instance
 * must not be shared by multiple IR operations!
 */
ir_visitor_status
ir_copy_propagation_visitor::visit(ir_dereference_variable *ir)
{
   /* Ignores the LHS.  Don't want to rewrite the LHS to point at some
    * other storage!
    */
   if (this->in_lhs) {
      this->in_lhs = false;
      return visit_continue;
   }

   ir_variable *var = ir->variable_referenced();

   foreach_iter(exec_list_iterator, iter, *this->acp) {
      acp_entry *entry = (acp_entry *)iter.get();

      if (var == entry->lhs) {
	 ir->var = entry->rhs;
	 this->progress = true;
	 break;
      }
   }

   return visit_continue;
}

ir_visitor_status
ir_copy_propagation_visitor::visit_enter(ir_call *ir)
{
   (void)ir;

   /* Note, if we were to do copy propagation to parameters of calls, we'd
    * have to be careful about out params.
    */
   return visit_continue_with_parent;
}

ir_visitor_status
ir_copy_propagation_visitor::visit_enter(ir_if *ir)
{
   ir->condition->accept(this);

   /* Do not traverse into the body of the if-statement since that is a
    * different basic block.
    */
   return visit_continue_with_parent;
}

static bool
propagate_copies(ir_instruction *ir, exec_list *acp)
{
   ir_copy_propagation_visitor v(acp);

   ir->accept(&v);

   return v.progress;
}

static void
kill_invalidated_copies(ir_assignment *ir, exec_list *acp)
{
   ir_variable *var = ir->lhs->variable_referenced();
   assert(var != NULL);

   foreach_iter(exec_list_iterator, iter, *acp) {
      acp_entry *entry = (acp_entry *)iter.get();

      if (entry->lhs == var || entry->rhs == var) {
	 entry->remove();
      }
   }
}

/**
 * Adds an entry to the available copy list if it's a plain assignment
 * of a variable to a variable.
 */
static void
add_copy(void *ctx, ir_assignment *ir, exec_list *acp)
{
   acp_entry *entry;

   if (ir->condition) {
      ir_constant *condition = ir->condition->as_constant();
      if (!condition || !condition->value.b[0])
	 return;
   }

   ir_variable *lhs_var = ir->lhs->whole_variable_referenced();
   ir_variable *rhs_var = ir->rhs->whole_variable_referenced();

   if ((lhs_var != NULL) && (rhs_var != NULL)) {
      entry = new(ctx) acp_entry(lhs_var, rhs_var);
      acp->push_tail(entry);
   }
}

static void
copy_propagation_basic_block(ir_instruction *first,
			     ir_instruction *last,
			     void *data)
{
   ir_instruction *ir;
   /* List of avaialble_copy */
   exec_list acp;
   bool *out_progress = (bool *)data;
   bool progress = false;

   void *ctx = talloc(NULL, void*);
   for (ir = first;; ir = (ir_instruction *)ir->next) {
      ir_assignment *ir_assign = ir->as_assignment();

      progress = propagate_copies(ir, &acp) || progress;

      if (ir_assign) {
	 kill_invalidated_copies(ir_assign, &acp);

	 add_copy(ctx, ir_assign, &acp);
      }
      if (ir == last)
	 break;
   }
   *out_progress = progress;
   talloc_free(ctx);
}

/**
 * Does a copy propagation pass on the code present in the instruction stream.
 */
bool
do_copy_propagation(exec_list *instructions)
{
   bool progress = false;

   call_for_basic_blocks(instructions, copy_propagation_basic_block, &progress);

   return progress;
}
<|endoftext|>


<commit_before>/*
 * Copyright © 2011 Intel Corporation
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice (including the next
 * paragraph) shall be included in all copies or substantial portions of the
 * Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 */

/**
 * \file lower_clip_distance.cpp
 *
 * This pass accounts for the difference between the way
 * gl_ClipDistance is declared in standard GLSL (as an array of
 * floats), and the way it is frequently implemented in hardware (as
 * a pair of vec4s, with four clip distances packed into each).
 *
 * The declaration of gl_ClipDistance is replaced with a declaration
 * of gl_ClipDistanceMESA, and any references to gl_ClipDistance are
 * translated to refer to gl_ClipDistanceMESA with the appropriate
 * swizzling of array indices.  For instance:
 *
 *   gl_ClipDistance[i]
 *
 * is translated into:
 *
 *   gl_ClipDistanceMESA[i>>2][i&3]
 *
 * Since some hardware may not internally represent gl_ClipDistance as a pair
 * of vec4's, this lowering pass is optional.  To enable it, set the
 * LowerClipDistance flag in gl_shader_compiler_options to true.
 */

#include "glsl_symbol_table.h"
#include "ir_hierarchical_visitor.h"
#include "ir.h"

class lower_clip_distance_visitor : public ir_hierarchical_visitor {
public:
   lower_clip_distance_visitor()
      : progress(false), old_clip_distance_var(NULL),
        new_clip_distance_var(NULL)
   {
   }

   virtual ir_visitor_status visit(ir_variable *);
   void create_indices(ir_rvalue*, ir_rvalue *&, ir_rvalue *&);
   virtual ir_visitor_status visit_leave(ir_dereference_array *);
   virtual ir_visitor_status visit_leave(ir_assignment *);
   void visit_new_assignment(ir_assignment *ir);
   virtual ir_visitor_status visit_leave(ir_call *);

   bool progress;

   /**
    * Pointer to the declaration of gl_ClipDistance, if found.
    */
   ir_variable *old_clip_distance_var;

   /**
    * Pointer to the newly-created gl_ClipDistanceMESA variable.
    */
   ir_variable *new_clip_distance_var;
};

/**
 * Replace any declaration of gl_ClipDistance as an array of floats with a
 * declaration of gl_ClipDistanceMESA as an array of vec4's.
 */
ir_visitor_status
lower_clip_distance_visitor::visit(ir_variable *ir)
{
   /* No point in looking for the declaration of gl_ClipDistance if
    * we've already found it.
    */
   if (this->old_clip_distance_var)
      return visit_continue;

   if (ir->name && strcmp(ir->name, "gl_ClipDistance") == 0) {
      this->progress = true;
      this->old_clip_distance_var = ir;
      assert (ir->type->is_array());
      assert (ir->type->element_type() == glsl_type::float_type);
      unsigned new_size = (ir->type->array_size() + 3) / 4;

      /* Clone the old var so that we inherit all of its properties */
      this->new_clip_distance_var = ir->clone(ralloc_parent(ir), NULL);

      /* And change the properties that we need to change */
      this->new_clip_distance_var->name
         = ralloc_strdup(this->new_clip_distance_var, "gl_ClipDistanceMESA");
      this->new_clip_distance_var->type
         = glsl_type::get_array_instance(glsl_type::vec4_type, new_size);
      this->new_clip_distance_var->max_array_access = ir->max_array_access / 4;

      ir->replace_with(this->new_clip_distance_var);
   }
   return visit_continue;
}

/**
 * Create the necessary GLSL rvalues to index into gl_ClipDistanceMESA based
 * on the rvalue previously used to index into gl_ClipDistance.
 *
 * \param array_index Selects one of the vec4's in gl_ClipDistanceMESA
 * \param swizzle_index Selects a component within the vec4 selected by
 *        array_index.
 */
void
lower_clip_distance_visitor::create_indices(ir_rvalue *old_index,
                                            ir_rvalue *&array_index,
                                            ir_rvalue *&swizzle_index)
{
   void *ctx = ralloc_parent(old_index);

   /* Make sure old_index is a signed int so that the bitwise "shift" and
    * "and" operations below type check properly.
    */
   if (old_index->type != glsl_type::int_type) {
      assert (old_index->type == glsl_type::uint_type);
      old_index = new(ctx) ir_expression(ir_unop_u2i, old_index);
   }

   ir_constant *old_index_constant = old_index->constant_expression_value();
   if (old_index_constant) {
      /* gl_ClipDistance is being accessed via a constant index.  Don't bother
       * creating expressions to calculate the lowered indices.  Just create
       * constants.
       */
      int const_val = old_index_constant->get_int_component(0);
      array_index = new(ctx) ir_constant(const_val / 4);
      swizzle_index = new(ctx) ir_constant(const_val % 4);
   } else {
      /* Create a variable to hold the value of old_index (so that we
       * don't compute it twice).
       */
      ir_variable *old_index_var = new(ctx) ir_variable(
         glsl_type::int_type, "clip_distance_index", ir_var_temporary);
      this->base_ir->insert_before(old_index_var);
      this->base_ir->insert_before(new(ctx) ir_assignment(
         new(ctx) ir_dereference_variable(old_index_var), old_index));

      /* Create the expression clip_distance_index / 4.  Do this as a bit
       * shift because that's likely to be more efficient.
       */
      array_index = new(ctx) ir_expression(
         ir_binop_rshift, new(ctx) ir_dereference_variable(old_index_var),
         new(ctx) ir_constant(2));

      /* Create the expression clip_distance_index % 4.  Do this as a bitwise
       * AND because that's likely to be more efficient.
       */
      swizzle_index = new(ctx) ir_expression(
         ir_binop_bit_and, new(ctx) ir_dereference_variable(old_index_var),
         new(ctx) ir_constant(3));
   }
}

/**
 * Replace any expression that indexes into the gl_ClipDistance array with an
 * expression that indexes into one of the vec4's in gl_ClipDistanceMESA and
 * accesses the appropriate component.
 */
ir_visitor_status
lower_clip_distance_visitor::visit_leave(ir_dereference_array *ir)
{
   /* If the gl_ClipDistance var hasn't been declared yet, then
    * there's no way this deref can refer to it.
    */
   if (!this->old_clip_distance_var)
      return visit_continue;

   ir_dereference_variable *old_var_ref = ir->array->as_dereference_variable();
   if (old_var_ref && old_var_ref->var == this->old_clip_distance_var) {
      this->progress = true;
      ir_rvalue *array_index;
      ir_rvalue *swizzle_index;
      this->create_indices(ir->array_index, array_index, swizzle_index);
      void *mem_ctx = ralloc_parent(ir);
      ir->array = new(mem_ctx) ir_dereference_array(
         this->new_clip_distance_var, array_index);
      ir->array_index = swizzle_index;
   }

   return visit_continue;
}

/**
 * Replace any assignment having gl_ClipDistance (undereferenced) as its LHS
 * or RHS with a sequence of assignments, one for each component of the array.
 * Each of these assignments is lowered to refer to gl_ClipDistanceMESA as
 * appropriate.
 */
ir_visitor_status
lower_clip_distance_visitor::visit_leave(ir_assignment *ir)
{
   ir_dereference_variable *lhs_var = ir->lhs->as_dereference_variable();
   ir_dereference_variable *rhs_var = ir->rhs->as_dereference_variable();
   if ((lhs_var && lhs_var->var == this->old_clip_distance_var)
       || (rhs_var && rhs_var->var == this->old_clip_distance_var)) {
      /* LHS or RHS of the assignment is the entire gl_ClipDistance array.
       * Since we are reshaping gl_ClipDistance from an array of floats to an
       * array of vec4's, this isn't going to work as a bulk assignment
       * anymore, so unroll it to element-by-element assignments and lower
       * each of them.
       *
       * Note: to unroll into element-by-element assignments, we need to make
       * clones of the LHS and RHS.  This is only safe if the LHS and RHS are
       * side-effect free.  Fortunately, we know that they are, because the
       * only kind of rvalue that can have side effects is an ir_call, and
       * ir_calls only appear (a) as a statement on their own, or (b) as the
       * RHS of an assignment that stores the result of the call in a
       * temporary variable.
       */
      void *ctx = ralloc_parent(ir);
      int array_size = this->old_clip_distance_var->type->array_size();
      for (int i = 0; i < array_size; ++i) {
         ir_dereference_array *new_lhs = new(ctx) ir_dereference_array(
            ir->lhs->clone(ctx, NULL), new(ctx) ir_constant(i));
         new_lhs->accept(this);
         ir_dereference_array *new_rhs = new(ctx) ir_dereference_array(
            ir->rhs->clone(ctx, NULL), new(ctx) ir_constant(i));
         new_rhs->accept(this);
         this->base_ir->insert_before(
            new(ctx) ir_assignment(new_lhs, new_rhs));
      }
      ir->remove();
   }

   return visit_continue;
}

/**
 * Set up base_ir properly and call visit_leave() on a newly created
 * ir_assignment node.  This is used in cases where we have to insert an
 * ir_assignment in a place where we know the hierarchical visitor won't see
 * it.
 */
void
lower_clip_distance_visitor::visit_new_assignment(ir_assignment *ir)
{
   ir_instruction *old_base_ir = this->base_ir;
   this->base_ir = ir;
   ir->accept(this);
   this->base_ir = old_base_ir;
}

/**
 * If gl_ClipDistance appears as an argument in an ir_call expression, replace
 * it with a temporary variable, and make sure the ir_call is preceded and/or
 * followed by assignments that copy the contents of the temporary variable to
 * and/or from gl_ClipDistance.  Each of these assignments is then lowered to
 * refer to gl_ClipDistanceMESA.
 */
ir_visitor_status
lower_clip_distance_visitor::visit_leave(ir_call *ir)
{
   void *ctx = ralloc_parent(ir);

   const exec_node *formal_param_node = ir->callee->parameters.head;
   const exec_node *actual_param_node = ir->actual_parameters.head;
   while (!actual_param_node->is_tail_sentinel()) {
      ir_variable *formal_param = (ir_variable *) formal_param_node;
      ir_rvalue *actual_param = (ir_rvalue *) actual_param_node;

      /* Advance formal_param_node and actual_param_node now so that we can
       * safely replace actual_param with another node, if necessary, below.
       */
      formal_param_node = formal_param_node->next;
      actual_param_node = actual_param_node->next;

      ir_dereference_variable *deref = actual_param->as_dereference_variable();
      if (deref && deref->var == this->old_clip_distance_var) {
         /* User is trying to pass the whole gl_ClipDistance array to a
          * function call.  Since we are reshaping gl_ClipDistance from an
          * array of floats to an array of vec4's, this isn't going to work
          * anymore, so use a temporary array instead.
          */
         ir_variable *temp_clip_distance = new(ctx) ir_variable(
            actual_param->type, "temp_clip_distance", ir_var_temporary);
         this->base_ir->insert_before(temp_clip_distance);
         actual_param->replace_with(
            new(ctx) ir_dereference_variable(temp_clip_distance));
         if (formal_param->mode == ir_var_function_in
             || formal_param->mode == ir_var_function_inout) {
            /* Copy from gl_ClipDistance to the temporary before the call.
             * Since we are going to insert this copy before the current
             * instruction, we need to visit it afterwards to make sure it
             * gets lowered.
             */
            ir_assignment *new_assignment = new(ctx) ir_assignment(
               new(ctx) ir_dereference_variable(temp_clip_distance),
               new(ctx) ir_dereference_variable(old_clip_distance_var));
            this->base_ir->insert_before(new_assignment);
            this->visit_new_assignment(new_assignment);
         }
         if (formal_param->mode == ir_var_function_out
             || formal_param->mode == ir_var_function_inout) {
            /* Copy from the temporary to gl_ClipDistance after the call.
             * Since visit_list_elements() has already decided which
             * instruction it's going to visit next, we need to visit
             * afterwards to make sure it gets lowered.
             */
            ir_assignment *new_assignment = new(ctx) ir_assignment(
               new(ctx) ir_dereference_variable(old_clip_distance_var),
               new(ctx) ir_dereference_variable(temp_clip_distance));
            this->base_ir->insert_after(new_assignment);
            this->visit_new_assignment(new_assignment);
         }
      }
   }

   return visit_continue;
}

bool
lower_clip_distance(gl_shader *shader)
{
   lower_clip_distance_visitor v;

   visit_list_elements(&v, shader->ir);

   if (v.new_clip_distance_var)
      shader->symbols->add_variable(v.new_clip_distance_var);

   return v.progress;
}
<commit_msg>glsl: Convert lower_clip_distance_visitor to be an ir_rvalue_visitor<commit_after>/*
 * Copyright © 2011 Intel Corporation
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice (including the next
 * paragraph) shall be included in all copies or substantial portions of the
 * Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 */

/**
 * \file lower_clip_distance.cpp
 *
 * This pass accounts for the difference between the way
 * gl_ClipDistance is declared in standard GLSL (as an array of
 * floats), and the way it is frequently implemented in hardware (as
 * a pair of vec4s, with four clip distances packed into each).
 *
 * The declaration of gl_ClipDistance is replaced with a declaration
 * of gl_ClipDistanceMESA, and any references to gl_ClipDistance are
 * translated to refer to gl_ClipDistanceMESA with the appropriate
 * swizzling of array indices.  For instance:
 *
 *   gl_ClipDistance[i]
 *
 * is translated into:
 *
 *   gl_ClipDistanceMESA[i>>2][i&3]
 *
 * Since some hardware may not internally represent gl_ClipDistance as a pair
 * of vec4's, this lowering pass is optional.  To enable it, set the
 * LowerClipDistance flag in gl_shader_compiler_options to true.
 */

#include "glsl_symbol_table.h"
#include "ir_rvalue_visitor.h"
#include "ir.h"

class lower_clip_distance_visitor : public ir_rvalue_visitor {
public:
   lower_clip_distance_visitor()
      : progress(false), old_clip_distance_var(NULL),
        new_clip_distance_var(NULL)
   {
   }

   virtual ir_visitor_status visit(ir_variable *);
   void create_indices(ir_rvalue*, ir_rvalue *&, ir_rvalue *&);
   virtual ir_visitor_status visit_leave(ir_assignment *);
   void visit_new_assignment(ir_assignment *ir);
   virtual ir_visitor_status visit_leave(ir_call *);

   virtual void handle_rvalue(ir_rvalue **rvalue);

   bool progress;

   /**
    * Pointer to the declaration of gl_ClipDistance, if found.
    */
   ir_variable *old_clip_distance_var;

   /**
    * Pointer to the newly-created gl_ClipDistanceMESA variable.
    */
   ir_variable *new_clip_distance_var;
};

/**
 * Replace any declaration of gl_ClipDistance as an array of floats with a
 * declaration of gl_ClipDistanceMESA as an array of vec4's.
 */
ir_visitor_status
lower_clip_distance_visitor::visit(ir_variable *ir)
{
   /* No point in looking for the declaration of gl_ClipDistance if
    * we've already found it.
    */
   if (this->old_clip_distance_var)
      return visit_continue;

   if (ir->name && strcmp(ir->name, "gl_ClipDistance") == 0) {
      this->progress = true;
      this->old_clip_distance_var = ir;
      assert (ir->type->is_array());
      assert (ir->type->element_type() == glsl_type::float_type);
      unsigned new_size = (ir->type->array_size() + 3) / 4;

      /* Clone the old var so that we inherit all of its properties */
      this->new_clip_distance_var = ir->clone(ralloc_parent(ir), NULL);

      /* And change the properties that we need to change */
      this->new_clip_distance_var->name
         = ralloc_strdup(this->new_clip_distance_var, "gl_ClipDistanceMESA");
      this->new_clip_distance_var->type
         = glsl_type::get_array_instance(glsl_type::vec4_type, new_size);
      this->new_clip_distance_var->max_array_access = ir->max_array_access / 4;

      ir->replace_with(this->new_clip_distance_var);
   }
   return visit_continue;
}

/**
 * Create the necessary GLSL rvalues to index into gl_ClipDistanceMESA based
 * on the rvalue previously used to index into gl_ClipDistance.
 *
 * \param array_index Selects one of the vec4's in gl_ClipDistanceMESA
 * \param swizzle_index Selects a component within the vec4 selected by
 *        array_index.
 */
void
lower_clip_distance_visitor::create_indices(ir_rvalue *old_index,
                                            ir_rvalue *&array_index,
                                            ir_rvalue *&swizzle_index)
{
   void *ctx = ralloc_parent(old_index);

   /* Make sure old_index is a signed int so that the bitwise "shift" and
    * "and" operations below type check properly.
    */
   if (old_index->type != glsl_type::int_type) {
      assert (old_index->type == glsl_type::uint_type);
      old_index = new(ctx) ir_expression(ir_unop_u2i, old_index);
   }

   ir_constant *old_index_constant = old_index->constant_expression_value();
   if (old_index_constant) {
      /* gl_ClipDistance is being accessed via a constant index.  Don't bother
       * creating expressions to calculate the lowered indices.  Just create
       * constants.
       */
      int const_val = old_index_constant->get_int_component(0);
      array_index = new(ctx) ir_constant(const_val / 4);
      swizzle_index = new(ctx) ir_constant(const_val % 4);
   } else {
      /* Create a variable to hold the value of old_index (so that we
       * don't compute it twice).
       */
      ir_variable *old_index_var = new(ctx) ir_variable(
         glsl_type::int_type, "clip_distance_index", ir_var_temporary);
      this->base_ir->insert_before(old_index_var);
      this->base_ir->insert_before(new(ctx) ir_assignment(
         new(ctx) ir_dereference_variable(old_index_var), old_index));

      /* Create the expression clip_distance_index / 4.  Do this as a bit
       * shift because that's likely to be more efficient.
       */
      array_index = new(ctx) ir_expression(
         ir_binop_rshift, new(ctx) ir_dereference_variable(old_index_var),
         new(ctx) ir_constant(2));

      /* Create the expression clip_distance_index % 4.  Do this as a bitwise
       * AND because that's likely to be more efficient.
       */
      swizzle_index = new(ctx) ir_expression(
         ir_binop_bit_and, new(ctx) ir_dereference_variable(old_index_var),
         new(ctx) ir_constant(3));
   }
}

void
lower_clip_distance_visitor::handle_rvalue(ir_rvalue **rv)
{
   /* If the gl_ClipDistance var hasn't been declared yet, then
    * there's no way this deref can refer to it.
    */
   if (!this->old_clip_distance_var || *rv == NULL)
      return;

   ir_dereference_array *const array_deref = (*rv)->as_dereference_array();
   if (array_deref == NULL)
      return;

   /* Replace any expression that indexes into the gl_ClipDistance array
    * with an expression that indexes into one of the vec4's in
    * gl_ClipDistanceMESA and accesses the appropriate component.
    */
   ir_dereference_variable *old_var_ref =
      array_deref->array->as_dereference_variable();
   if (old_var_ref && old_var_ref->var == this->old_clip_distance_var) {
      this->progress = true;
      ir_rvalue *array_index;
      ir_rvalue *swizzle_index;
      this->create_indices(array_deref->array_index, array_index, swizzle_index);
      void *mem_ctx = ralloc_parent(array_deref);
      array_deref->array = new(mem_ctx) ir_dereference_array(
         this->new_clip_distance_var, array_index);
      array_deref->array_index = swizzle_index;
   }
}

/**
 * Replace any assignment having gl_ClipDistance (undereferenced) as its LHS
 * or RHS with a sequence of assignments, one for each component of the array.
 * Each of these assignments is lowered to refer to gl_ClipDistanceMESA as
 * appropriate.
 */
ir_visitor_status
lower_clip_distance_visitor::visit_leave(ir_assignment *ir)
{
   ir_dereference_variable *lhs_var = ir->lhs->as_dereference_variable();
   ir_dereference_variable *rhs_var = ir->rhs->as_dereference_variable();
   if ((lhs_var && lhs_var->var == this->old_clip_distance_var)
       || (rhs_var && rhs_var->var == this->old_clip_distance_var)) {
      /* LHS or RHS of the assignment is the entire gl_ClipDistance array.
       * Since we are reshaping gl_ClipDistance from an array of floats to an
       * array of vec4's, this isn't going to work as a bulk assignment
       * anymore, so unroll it to element-by-element assignments and lower
       * each of them.
       *
       * Note: to unroll into element-by-element assignments, we need to make
       * clones of the LHS and RHS.  This is only safe if the LHS and RHS are
       * side-effect free.  Fortunately, we know that they are, because the
       * only kind of rvalue that can have side effects is an ir_call, and
       * ir_calls only appear (a) as a statement on their own, or (b) as the
       * RHS of an assignment that stores the result of the call in a
       * temporary variable.
       */
      void *ctx = ralloc_parent(ir);
      int array_size = this->old_clip_distance_var->type->array_size();
      for (int i = 0; i < array_size; ++i) {
         ir_dereference_array *new_lhs = new(ctx) ir_dereference_array(
            ir->lhs->clone(ctx, NULL), new(ctx) ir_constant(i));
         this->handle_rvalue((ir_rvalue **) &new_lhs);
         ir_dereference_array *new_rhs = new(ctx) ir_dereference_array(
            ir->rhs->clone(ctx, NULL), new(ctx) ir_constant(i));
         this->handle_rvalue((ir_rvalue **) &new_rhs);
         this->base_ir->insert_before(
            new(ctx) ir_assignment(new_lhs, new_rhs));
      }
      ir->remove();

      return visit_continue;
   }

   /* Handle the LHS as if it were an r-value.  Normally
    * rvalue_visit(ir_assignment *) only visits the RHS, but we need to lower
    * expressions in the LHS as well.
    */
   handle_rvalue((ir_rvalue **)&ir->lhs);
   return rvalue_visit(ir);
}

/**
 * Set up base_ir properly and call visit_leave() on a newly created
 * ir_assignment node.  This is used in cases where we have to insert an
 * ir_assignment in a place where we know the hierarchical visitor won't see
 * it.
 */
void
lower_clip_distance_visitor::visit_new_assignment(ir_assignment *ir)
{
   ir_instruction *old_base_ir = this->base_ir;
   this->base_ir = ir;
   ir->accept(this);
   this->base_ir = old_base_ir;
}

/**
 * If gl_ClipDistance appears as an argument in an ir_call expression, replace
 * it with a temporary variable, and make sure the ir_call is preceded and/or
 * followed by assignments that copy the contents of the temporary variable to
 * and/or from gl_ClipDistance.  Each of these assignments is then lowered to
 * refer to gl_ClipDistanceMESA.
 */
ir_visitor_status
lower_clip_distance_visitor::visit_leave(ir_call *ir)
{
   void *ctx = ralloc_parent(ir);

   const exec_node *formal_param_node = ir->callee->parameters.head;
   const exec_node *actual_param_node = ir->actual_parameters.head;
   while (!actual_param_node->is_tail_sentinel()) {
      ir_variable *formal_param = (ir_variable *) formal_param_node;
      ir_rvalue *actual_param = (ir_rvalue *) actual_param_node;

      /* Advance formal_param_node and actual_param_node now so that we can
       * safely replace actual_param with another node, if necessary, below.
       */
      formal_param_node = formal_param_node->next;
      actual_param_node = actual_param_node->next;

      ir_dereference_variable *deref = actual_param->as_dereference_variable();
      if (deref && deref->var == this->old_clip_distance_var) {
         /* User is trying to pass the whole gl_ClipDistance array to a
          * function call.  Since we are reshaping gl_ClipDistance from an
          * array of floats to an array of vec4's, this isn't going to work
          * anymore, so use a temporary array instead.
          */
         ir_variable *temp_clip_distance = new(ctx) ir_variable(
            actual_param->type, "temp_clip_distance", ir_var_temporary);
         this->base_ir->insert_before(temp_clip_distance);
         actual_param->replace_with(
            new(ctx) ir_dereference_variable(temp_clip_distance));
         if (formal_param->mode == ir_var_function_in
             || formal_param->mode == ir_var_function_inout) {
            /* Copy from gl_ClipDistance to the temporary before the call.
             * Since we are going to insert this copy before the current
             * instruction, we need to visit it afterwards to make sure it
             * gets lowered.
             */
            ir_assignment *new_assignment = new(ctx) ir_assignment(
               new(ctx) ir_dereference_variable(temp_clip_distance),
               new(ctx) ir_dereference_variable(old_clip_distance_var));
            this->base_ir->insert_before(new_assignment);
            this->visit_new_assignment(new_assignment);
         }
         if (formal_param->mode == ir_var_function_out
             || formal_param->mode == ir_var_function_inout) {
            /* Copy from the temporary to gl_ClipDistance after the call.
             * Since visit_list_elements() has already decided which
             * instruction it's going to visit next, we need to visit
             * afterwards to make sure it gets lowered.
             */
            ir_assignment *new_assignment = new(ctx) ir_assignment(
               new(ctx) ir_dereference_variable(old_clip_distance_var),
               new(ctx) ir_dereference_variable(temp_clip_distance));
            this->base_ir->insert_after(new_assignment);
            this->visit_new_assignment(new_assignment);
         }
      }
   }

   return rvalue_visit(ir);
}

bool
lower_clip_distance(gl_shader *shader)
{
   lower_clip_distance_visitor v;

   visit_list_elements(&v, shader->ir);

   if (v.new_clip_distance_var)
      shader->symbols->add_variable(v.new_clip_distance_var);

   return v.progress;
}
<|endoftext|>


<commit_before>/*The MIT License (MIT)

Copyright (c) 2015 Jens Malmborg

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/

#include <script/scripthelper.h>
#include <script/script-engine.h>
#include <script/scriptobjecthelper.h>
#include "graphics-device.h"
#include "texture-collection.h"
#include "vertex-declaration.h"
#include "window.h"
#include "vertex-data-state.h"

using namespace v8;

namespace {

void SetVertexDataState(const FunctionCallbackInfo<Value>& args) {
    HandleScope scope(args.GetIsolate());
    ScriptHelper helper(args.GetIsolate());
    auto vertexBuffer = helper.GetObject<VertexDataState>(args[0]);
    helper.GetObject<GraphicsDevice>(args.Holder())->
            SetVertexDataState(vertexBuffer);
}

void SetBlendState(const FunctionCallbackInfo<Value>& args) {
    HandleScope scope(args.GetIsolate());
    ScriptHelper helper(args.GetIsolate());

    auto state = helper.GetString(args[0]);
    if (state == "additive") {
        helper.GetObject<GraphicsDevice>(args.Holder())->
                SetBlendState(BlendState::Additive);
    }
    else if (state == "alphaBlend") {
        helper.GetObject<GraphicsDevice>(args.Holder())->
                SetBlendState(BlendState::AlphaBlend);
    }
    else if (state == "opaque") {
        helper.GetObject<GraphicsDevice>(args.Holder())->
                SetBlendState(BlendState::Opaque);
    }
    else {
        ScriptEngine::current().ThrowTypeError(
                "Couln't set blend state to '" + state + "'.");
    }
}

void SetDepthStencilState(const FunctionCallbackInfo<Value>& args) {
    HandleScope scope(args.GetIsolate());
    ScriptHelper helper(args.GetIsolate());

    auto state = helper.GetString(args[0]);
    if (state == "default") {
        helper.GetObject<GraphicsDevice>(args.Holder())->
                SetDepthStencilState(DepthStencilState::Default);
    }
    else if (state == "depthRead") {
        helper.GetObject<GraphicsDevice>(args.Holder())->
                SetDepthStencilState(DepthStencilState::DepthRead);
    }
    else if (state == "none") {
        helper.GetObject<GraphicsDevice>(args.Holder())->
                SetDepthStencilState(DepthStencilState::None);
    }
    else {
        ScriptEngine::current().ThrowTypeError(
                "Couln't set depth stencil state to '" + state + "'.");
    }
}

}

GraphicsDevice::GraphicsDevice(Isolate *isolate, Window *window) :
        ScriptObjectWrap(isolate), textures_(isolate, this), window_(window) {
    textures_.InstallAsObject("textures", this->v8Object());
    SetBlendState(BlendState::Opaque);
    SetDepthStencilState(DepthStencilState::Default);
}

void GraphicsDevice::Clear(float r, float g, float b, float a) {
    glClearColor(r, g, b, a);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
}

void GraphicsDevice::DrawVertices(PrimitiveType primitiveType,
                                    int startVertex, int primitiveCount) {
    if (vertexDataState_ == nullptr) {
        throw std::runtime_error(
                "Vertex data state must be set before drawing vertices.");
    }
    if (shaderProgram_ == nullptr) {
        throw std::runtime_error(
                "Shader program must be set before drawing vertices.");
    }
    switch (primitiveType) {
        case PrimitiveType::TriangleList:
            glDrawArrays(GL_TRIANGLES, startVertex, primitiveCount * 3);
            break;
        case PrimitiveType::PointList:
            glDrawArrays(GL_POINTS, startVertex, primitiveCount);
            break;
        case PrimitiveType::LineList:
            glDrawArrays(GL_LINES, startVertex, primitiveCount * 2);
            break;
    }
}

void GraphicsDevice::DrawElements(PrimitiveType primitiveType,
                                  int startIndex, int primitiveCount) {
    if (vertexDataState_ == nullptr) {
        throw std::runtime_error(
                "Vertex data state must be set before drawing elements.");
    }
    if (shaderProgram_ == nullptr) {
        throw std::runtime_error(
                "Shader program must be set before drawing elements.");
    }
    switch (primitiveType) {
        case PrimitiveType::TriangleList:
            glDrawElements(GL_TRIANGLES, primitiveCount * 3, GL_UNSIGNED_INT,
                           (void*)(startIndex * sizeof(GLuint)));
            break;
        case PrimitiveType::PointList:
            glDrawElements(GL_TRIANGLES, primitiveCount, GL_UNSIGNED_INT,
                           (void*)(startIndex * sizeof(GLuint)));
            break;
        case PrimitiveType::LineList:
            glDrawElements(GL_TRIANGLES, primitiveCount * 2, GL_UNSIGNED_INT,
                           (void*)(startIndex * sizeof(GLuint)));
            break;
    }
}

void GraphicsDevice::Present() {
    glfwSwapBuffers(window_->glfwWindow());
}

void GraphicsDevice::SetShaderProgram(ShaderProgram *shaderProgram) {
    if (shaderProgram != nullptr && shaderProgram != shaderProgram_) {
        glUseProgram(shaderProgram->glProgram());
    }
    shaderProgram_ = shaderProgram;
}

void GraphicsDevice::SetSynchronizeWithVerticalRetrace(bool value) {
    glfwSwapInterval(value);
}

void GraphicsDevice::SetTexture(int index, Texture2D* texture) {
    if (textures_[index] == texture) {
        return;
    }
    textures_[index] = texture;
    switch (index) {
        case 0:
            glActiveTexture(GL_TEXTURE0);
            break;
        case 1:
            glActiveTexture(GL_TEXTURE1);
            break;
        case 2:
            glActiveTexture(GL_TEXTURE2);
            break;
        case 3:
            glActiveTexture(GL_TEXTURE3);
            break;
        default:
            throw std::runtime_error("Unknown texture unit");
    }
    if (texture == nullptr) {
        glBindTexture(GL_TEXTURE_2D, 0);
    }
    else {
        glBindTexture(GL_TEXTURE_2D, texture->glTexture());
    }
}

void GraphicsDevice::SetVertexDataState(VertexDataState *vertexDataState) {
    if (vertexDataState == nullptr) {
        glBindVertexArray(0);
    }
    else if (vertexDataState != vertexDataState_) {
        glBindVertexArray(vertexDataState->glVertexArray());
    }
    vertexDataState_ = vertexDataState;
}

void GraphicsDevice::SetBlendState(BlendState state) {
    switch (state) {
        case BlendState::Additive: {
            glEnable(GL_BLEND);
            glBlendFunc(GL_SRC_ALPHA, GL_ONE);
            break;
        }
        case BlendState::AlphaBlend: {
            glEnable(GL_BLEND);
            glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
            break;
        }
        case BlendState::Opaque: {
            glDisable(GL_BLEND);
            break;
        }
    }
}

void GraphicsDevice::SetDepthStencilState(DepthStencilState state) {
    switch (state) {
        case DepthStencilState::Default: {
            glEnable(GL_DEPTH_TEST);
            glDepthMask(GL_TRUE);
            break;
        }
        case DepthStencilState::DepthRead: {
            glEnable(GL_DEPTH_TEST);
            glDepthMask(GL_FALSE);
            break;
        }
        case DepthStencilState::None: {
            glDisable(GL_DEPTH_TEST);
            glDepthMask(GL_FALSE);
            break;
        }
    }
}

void GraphicsDevice::Initialize() {
    ScriptObjectWrap::Initialize();
    SetFunction("clear", Clear);
    SetFunction("drawVertices", DrawVertices);
    SetFunction("drawElements", DrawElements);
    SetFunction("present", Present);
    SetFunction("setShaderProgram", SetShaderProgram);
    SetFunction("setSynchronizeWithVerticalRetrace",
                SetSynchronizeWithVerticalRetrace);
    SetFunction("setVertexDataState", ::SetVertexDataState);
    SetFunction("setBlendState", ::SetBlendState);
    SetFunction("setDepthStencilState", ::SetDepthStencilState);
}

void GraphicsDevice::Clear(const FunctionCallbackInfo<Value>& args) {
    HandleScope scope(args.GetIsolate());
    ScriptObjectHelper options(args.GetIsolate(), args[0]->ToObject());

    auto r = options.GetFloat("r");
    auto g = options.GetFloat("g");
    auto b = options.GetFloat("b");
    auto a = options.GetFloat("a");

    GetInternalObject(args.Holder())->Clear(r, g, b, a);
}

void GraphicsDevice::DrawVertices(const FunctionCallbackInfo<Value> &args) {
    HandleScope scope(args.GetIsolate());
    ScriptObjectHelper options(args.GetIsolate(), args[0]->ToObject());

    auto primitiveType = options.GetString("primitiveType");
    auto vertexStart = options.GetInteger("vertexStart");
    auto primitiveCount = options.GetInteger("primitiveCount");

    PrimitiveType primitive;
    if (primitiveType == "triangleList") {
        primitive = PrimitiveType::TriangleList;
    }
    else if (primitiveType == "pointList") {
        primitive = PrimitiveType::PointList;
    }
    else if (primitiveType == "lineList") {
        primitive = PrimitiveType::LineList;
    }

    auto graphics = GetInternalObject(args.Holder());
    try {
        graphics->DrawVertices(primitive, vertexStart, primitiveCount);
    }
    catch (std::exception& ex) {
        ScriptEngine::current().ThrowTypeError(ex.what());
    }
}

void GraphicsDevice::DrawElements(const FunctionCallbackInfo<Value> &args) {
    HandleScope scope(args.GetIsolate());
    ScriptObjectHelper options(args.GetIsolate(), args[0]->ToObject());

    auto primitiveType = options.GetString("primitiveType");
    auto indexStart = options.GetInteger("indexStart");
    auto primitiveCount = options.GetInteger("primitiveCount");

    PrimitiveType primitive;
    if (primitiveType == "triangleList") {
        primitive = PrimitiveType::TriangleList;
    }
    else if (primitiveType == "pointList") {
        primitive = PrimitiveType::PointList;
    }
    else if (primitiveType == "lineList") {
        primitive = PrimitiveType::LineList;
    }

    auto graphics = GetInternalObject(args.Holder());
    try {
        graphics->DrawElements(primitive, indexStart, primitiveCount);
    }
    catch (std::exception& ex) {
        ScriptEngine::current().ThrowTypeError(ex.what());
    }
}

void GraphicsDevice::Present(const FunctionCallbackInfo<Value>& args) {
    HandleScope scope(args.GetIsolate());
    GetInternalObject(args.Holder())->Present();
}

void GraphicsDevice::SetShaderProgram(const FunctionCallbackInfo<Value>& args) {
    HandleScope scope(args.GetIsolate());
    ScriptHelper helper(args.GetIsolate());
    auto shaderProgram = helper.GetObject<ShaderProgram>(args[0]);
    GetInternalObject(args.Holder())->SetShaderProgram(shaderProgram);
}

void GraphicsDevice::SetSynchronizeWithVerticalRetrace(
        const FunctionCallbackInfo<Value>& args) {
    HandleScope scope(args.GetIsolate());
    ScriptHelper helper(args.GetIsolate());
    auto value = helper.GetBoolean(args[0]);
    GetInternalObject(args.Holder())->SetSynchronizeWithVerticalRetrace(value);
}
<commit_msg>Fixed spelling error.<commit_after>/*The MIT License (MIT)

Copyright (c) 2015 Jens Malmborg

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/

#include <script/scripthelper.h>
#include <script/script-engine.h>
#include <script/scriptobjecthelper.h>
#include "graphics-device.h"
#include "texture-collection.h"
#include "vertex-declaration.h"
#include "window.h"
#include "vertex-data-state.h"

using namespace v8;

namespace {

void SetVertexDataState(const FunctionCallbackInfo<Value>& args) {
    HandleScope scope(args.GetIsolate());
    ScriptHelper helper(args.GetIsolate());
    auto vertexBuffer = helper.GetObject<VertexDataState>(args[0]);
    helper.GetObject<GraphicsDevice>(args.Holder())->
            SetVertexDataState(vertexBuffer);
}

void SetBlendState(const FunctionCallbackInfo<Value>& args) {
    HandleScope scope(args.GetIsolate());
    ScriptHelper helper(args.GetIsolate());

    auto state = helper.GetString(args[0]);
    if (state == "additive") {
        helper.GetObject<GraphicsDevice>(args.Holder())->
                SetBlendState(BlendState::Additive);
    }
    else if (state == "alphaBlend") {
        helper.GetObject<GraphicsDevice>(args.Holder())->
                SetBlendState(BlendState::AlphaBlend);
    }
    else if (state == "opaque") {
        helper.GetObject<GraphicsDevice>(args.Holder())->
                SetBlendState(BlendState::Opaque);
    }
    else {
        ScriptEngine::current().ThrowTypeError(
                "Couldn't set blend state to '" + state + "'.");
    }
}

void SetDepthStencilState(const FunctionCallbackInfo<Value>& args) {
    HandleScope scope(args.GetIsolate());
    ScriptHelper helper(args.GetIsolate());

    auto state = helper.GetString(args[0]);
    if (state == "default") {
        helper.GetObject<GraphicsDevice>(args.Holder())->
                SetDepthStencilState(DepthStencilState::Default);
    }
    else if (state == "depthRead") {
        helper.GetObject<GraphicsDevice>(args.Holder())->
                SetDepthStencilState(DepthStencilState::DepthRead);
    }
    else if (state == "none") {
        helper.GetObject<GraphicsDevice>(args.Holder())->
                SetDepthStencilState(DepthStencilState::None);
    }
    else {
        ScriptEngine::current().ThrowTypeError(
                "Couldn't set depth stencil state to '" + state + "'.");
    }
}

}

GraphicsDevice::GraphicsDevice(Isolate *isolate, Window *window) :
        ScriptObjectWrap(isolate), textures_(isolate, this), window_(window) {
    textures_.InstallAsObject("textures", this->v8Object());
    SetBlendState(BlendState::Opaque);
    SetDepthStencilState(DepthStencilState::Default);
}

void GraphicsDevice::Clear(float r, float g, float b, float a) {
    glClearColor(r, g, b, a);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
}

void GraphicsDevice::DrawVertices(PrimitiveType primitiveType,
                                    int startVertex, int primitiveCount) {
    if (vertexDataState_ == nullptr) {
        throw std::runtime_error(
                "Vertex data state must be set before drawing vertices.");
    }
    if (shaderProgram_ == nullptr) {
        throw std::runtime_error(
                "Shader program must be set before drawing vertices.");
    }
    switch (primitiveType) {
        case PrimitiveType::TriangleList:
            glDrawArrays(GL_TRIANGLES, startVertex, primitiveCount * 3);
            break;
        case PrimitiveType::PointList:
            glDrawArrays(GL_POINTS, startVertex, primitiveCount);
            break;
        case PrimitiveType::LineList:
            glDrawArrays(GL_LINES, startVertex, primitiveCount * 2);
            break;
    }
}

void GraphicsDevice::DrawElements(PrimitiveType primitiveType,
                                  int startIndex, int primitiveCount) {
    if (vertexDataState_ == nullptr) {
        throw std::runtime_error(
                "Vertex data state must be set before drawing elements.");
    }
    if (shaderProgram_ == nullptr) {
        throw std::runtime_error(
                "Shader program must be set before drawing elements.");
    }
    switch (primitiveType) {
        case PrimitiveType::TriangleList:
            glDrawElements(GL_TRIANGLES, primitiveCount * 3, GL_UNSIGNED_INT,
                           (void*)(startIndex * sizeof(GLuint)));
            break;
        case PrimitiveType::PointList:
            glDrawElements(GL_TRIANGLES, primitiveCount, GL_UNSIGNED_INT,
                           (void*)(startIndex * sizeof(GLuint)));
            break;
        case PrimitiveType::LineList:
            glDrawElements(GL_TRIANGLES, primitiveCount * 2, GL_UNSIGNED_INT,
                           (void*)(startIndex * sizeof(GLuint)));
            break;
    }
}

void GraphicsDevice::Present() {
    glfwSwapBuffers(window_->glfwWindow());
}

void GraphicsDevice::SetShaderProgram(ShaderProgram *shaderProgram) {
    if (shaderProgram != nullptr && shaderProgram != shaderProgram_) {
        glUseProgram(shaderProgram->glProgram());
    }
    shaderProgram_ = shaderProgram;
}

void GraphicsDevice::SetSynchronizeWithVerticalRetrace(bool value) {
    glfwSwapInterval(value);
}

void GraphicsDevice::SetTexture(int index, Texture2D* texture) {
    if (textures_[index] == texture) {
        return;
    }
    textures_[index] = texture;
    switch (index) {
        case 0:
            glActiveTexture(GL_TEXTURE0);
            break;
        case 1:
            glActiveTexture(GL_TEXTURE1);
            break;
        case 2:
            glActiveTexture(GL_TEXTURE2);
            break;
        case 3:
            glActiveTexture(GL_TEXTURE3);
            break;
        default:
            throw std::runtime_error("Unknown texture unit");
    }
    if (texture == nullptr) {
        glBindTexture(GL_TEXTURE_2D, 0);
    }
    else {
        glBindTexture(GL_TEXTURE_2D, texture->glTexture());
    }
}

void GraphicsDevice::SetVertexDataState(VertexDataState *vertexDataState) {
    if (vertexDataState == nullptr) {
        glBindVertexArray(0);
    }
    else if (vertexDataState != vertexDataState_) {
        glBindVertexArray(vertexDataState->glVertexArray());
    }
    vertexDataState_ = vertexDataState;
}

void GraphicsDevice::SetBlendState(BlendState state) {
    switch (state) {
        case BlendState::Additive: {
            glEnable(GL_BLEND);
            glBlendFunc(GL_SRC_ALPHA, GL_ONE);
            break;
        }
        case BlendState::AlphaBlend: {
            glEnable(GL_BLEND);
            glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
            break;
        }
        case BlendState::Opaque: {
            glDisable(GL_BLEND);
            break;
        }
    }
}

void GraphicsDevice::SetDepthStencilState(DepthStencilState state) {
    switch (state) {
        case DepthStencilState::Default: {
            glEnable(GL_DEPTH_TEST);
            glDepthMask(GL_TRUE);
            break;
        }
        case DepthStencilState::DepthRead: {
            glEnable(GL_DEPTH_TEST);
            glDepthMask(GL_FALSE);
            break;
        }
        case DepthStencilState::None: {
            glDisable(GL_DEPTH_TEST);
            glDepthMask(GL_FALSE);
            break;
        }
    }
}

void GraphicsDevice::Initialize() {
    ScriptObjectWrap::Initialize();
    SetFunction("clear", Clear);
    SetFunction("drawVertices", DrawVertices);
    SetFunction("drawElements", DrawElements);
    SetFunction("present", Present);
    SetFunction("setShaderProgram", SetShaderProgram);
    SetFunction("setSynchronizeWithVerticalRetrace",
                SetSynchronizeWithVerticalRetrace);
    SetFunction("setVertexDataState", ::SetVertexDataState);
    SetFunction("setBlendState", ::SetBlendState);
    SetFunction("setDepthStencilState", ::SetDepthStencilState);
}

void GraphicsDevice::Clear(const FunctionCallbackInfo<Value>& args) {
    HandleScope scope(args.GetIsolate());
    ScriptObjectHelper options(args.GetIsolate(), args[0]->ToObject());

    auto r = options.GetFloat("r");
    auto g = options.GetFloat("g");
    auto b = options.GetFloat("b");
    auto a = options.GetFloat("a");

    GetInternalObject(args.Holder())->Clear(r, g, b, a);
}

void GraphicsDevice::DrawVertices(const FunctionCallbackInfo<Value> &args) {
    HandleScope scope(args.GetIsolate());
    ScriptObjectHelper options(args.GetIsolate(), args[0]->ToObject());

    auto primitiveType = options.GetString("primitiveType");
    auto vertexStart = options.GetInteger("vertexStart");
    auto primitiveCount = options.GetInteger("primitiveCount");

    PrimitiveType primitive;
    if (primitiveType == "triangleList") {
        primitive = PrimitiveType::TriangleList;
    }
    else if (primitiveType == "pointList") {
        primitive = PrimitiveType::PointList;
    }
    else if (primitiveType == "lineList") {
        primitive = PrimitiveType::LineList;
    }

    auto graphics = GetInternalObject(args.Holder());
    try {
        graphics->DrawVertices(primitive, vertexStart, primitiveCount);
    }
    catch (std::exception& ex) {
        ScriptEngine::current().ThrowTypeError(ex.what());
    }
}

void GraphicsDevice::DrawElements(const FunctionCallbackInfo<Value> &args) {
    HandleScope scope(args.GetIsolate());
    ScriptObjectHelper options(args.GetIsolate(), args[0]->ToObject());

    auto primitiveType = options.GetString("primitiveType");
    auto indexStart = options.GetInteger("indexStart");
    auto primitiveCount = options.GetInteger("primitiveCount");

    PrimitiveType primitive;
    if (primitiveType == "triangleList") {
        primitive = PrimitiveType::TriangleList;
    }
    else if (primitiveType == "pointList") {
        primitive = PrimitiveType::PointList;
    }
    else if (primitiveType == "lineList") {
        primitive = PrimitiveType::LineList;
    }

    auto graphics = GetInternalObject(args.Holder());
    try {
        graphics->DrawElements(primitive, indexStart, primitiveCount);
    }
    catch (std::exception& ex) {
        ScriptEngine::current().ThrowTypeError(ex.what());
    }
}

void GraphicsDevice::Present(const FunctionCallbackInfo<Value>& args) {
    HandleScope scope(args.GetIsolate());
    GetInternalObject(args.Holder())->Present();
}

void GraphicsDevice::SetShaderProgram(const FunctionCallbackInfo<Value>& args) {
    HandleScope scope(args.GetIsolate());
    ScriptHelper helper(args.GetIsolate());
    auto shaderProgram = helper.GetObject<ShaderProgram>(args[0]);
    GetInternalObject(args.Holder())->SetShaderProgram(shaderProgram);
}

void GraphicsDevice::SetSynchronizeWithVerticalRetrace(
        const FunctionCallbackInfo<Value>& args) {
    HandleScope scope(args.GetIsolate());
    ScriptHelper helper(args.GetIsolate());
    auto value = helper.GetBoolean(args[0]);
    GetInternalObject(args.Holder())->SetSynchronizeWithVerticalRetrace(value);
}
<|endoftext|>


<commit_before>// MGBench: Multi-GPU Computing Benchmark Suite
// Copyright (c) 2016, Tal Ben-Nun
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
//   this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice,
//   this list of conditions and the following disclaimer in the documentation
//   and/or other materials provided with the distribution.
// * Neither the names of the copyright holders nor the names of its
//   contributors may be used to endorse or promote products derived from this
//   software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.

#include <cstdio>
#include <cstdlib>
#include <iostream>

#include <cuda_runtime.h>

static void HandleError(const char *file, int line, cudaError_t err)
{
    printf("ERROR in %s:%d: %s (%d)\n", file, line,
           cudaGetErrorString(err), err);
    cudaGetLastError();
}

// CUDA assertions
#define CUDA_CHECK(err) do { cudaError_t errr = (err); if(errr != cudaSuccess) { HandleError(__FILE__, __LINE__, errr); exit(1); } } while(0)

// Device capability helper macros
#define CAP(cap) NCAP(cap, cap)
#define NCAP(cap, name) ((props.cap) ? (#name " ") : "")

int main(int argc, char **argv)
{
    int ndevs = 0;
    if (cudaGetDeviceCount(&ndevs) != cudaSuccess)
        return 1;

    int version = 0;
    CUDA_CHECK(cudaDriverGetVersion(&version));
    std::cout << "Driver version: " << (version / 1000) << "."
              << ((version % 100) / 10) << std::endl;

    version = 0;
    CUDA_CHECK(cudaRuntimeGetVersion(&version));
    std::cout << "Runtime version: " << (version / 1000) << "."
              << ((version % 100) / 10) << std::endl;
    std::cout << std::endl;

    // Print information for each GPU
    for (int i = 0; i < ndevs; ++i)
    {
        CUDA_CHECK(cudaSetDevice(i));
        cudaDeviceProp props;
        CUDA_CHECK(cudaGetDeviceProperties(&props, i));

        std::cout << "GPU " << (i + 1) << ": " << props.name << " ("
                  << props.pciDomainID << "/" << props.pciBusID
                  << "/" << props.pciDeviceID << ")" << std::endl

                  << "Global memory: " << (props.totalGlobalMem/1024.0/1024.0)
                  << " MB" << std::endl
                  << "Constant memory: " << props.totalConstMem
                  << " bytes" << std::endl
                  << "Shared memory: " << props.sharedMemPerBlock
                  << " bytes" << std::endl
                  << "Registers: " << props.regsPerBlock << std::endl
                  << "Warp size: " << props.warpSize << std::endl
                  << "Multiprocessors: " << props.multiProcessorCount
                  << std::endl
                  << "Copy engines: " << props.asyncEngineCount << std::endl
                  << "Clock rate: " << (props.clockRate / 1e6)
                  << " GHz" << std::endl
                  << "Threads per MP: " << props.maxThreadsPerMultiProcessor
                  << std::endl
                  << "Threads per block: " << props.maxThreadsPerBlock
                  << std::endl
                  << "Max block size: " << props.maxThreadsDim[0] << "x"
                  << props.maxThreadsDim[1] << "x" << props.maxThreadsDim[2]
                  << std::endl
                  << "Max grid size: " << props.maxGridSize[0] << "x"
                  << props.maxGridSize[1] << "x" << props.maxGridSize[2]
                  << std::endl
                  << "Pitch: " << props.memPitch << " bytes" << std::endl;

        std::cout << "Caps: " << NCAP(ECCEnabled, ecc)
                  << NCAP(deviceOverlap, overlap)
                  << NCAP(unifiedAddressing, uva)
                  << NCAP(kernelExecTimeoutEnabled, timeout)
                  << CAP(integrated) << NCAP(canMapHostMemory, hostdma)
                  << CAP(surfaceAlignment) << CAP(tccDriver) << std::endl;
        std::cout << std::endl;
    }

    std::cout << "DMA access: " << std::endl;
    int tmp = 0;

    // Print top row
    printf("   | ");
    for (int i = 0; i < ndevs; ++i)
        printf("%2d ", i + 1);
    printf("\n---+");
    for (int i = 0; i < ndevs; ++i)
        printf("---");
    printf("\n");

    for (int i = 0; i < ndevs; ++i)
    {
        printf("%2d | ", i + 1);
        for (int j = 0; j < ndevs; ++j)
        {
            if (i == j)
            {
                printf(" x ");
                continue;
            }

            cudaDeviceCanAccessPeer(&tmp, i, j);
            printf("%2d ", tmp ? 1 : 0);
        }
        printf("\n");
    }

    return 0;
}
<commit_msg>devinfo: inspect specific gpu<commit_after>// MGBench: Multi-GPU Computing Benchmark Suite
// Copyright (c) 2016, Tal Ben-Nun
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
//   this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice,
//   this list of conditions and the following disclaimer in the documentation
//   and/or other materials provided with the distribution.
// * Neither the names of the copyright holders nor the names of its
//   contributors may be used to endorse or promote products derived from this
//   software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.

#include <cstdio>
#include <cstdlib>
#include <iostream>

#include <cuda_runtime.h>

static void HandleError(const char *file, int line, cudaError_t err)
{
    printf("ERROR in %s:%d: %s (%d)\n", file, line,
           cudaGetErrorString(err), err);
    cudaGetLastError();
}

// CUDA assertions
#define CUDA_CHECK(err) do { cudaError_t errr = (err); if(errr != cudaSuccess) { HandleError(__FILE__, __LINE__, errr); exit(1); } } while(0)

// Device capability helper macros
#define CAP(cap) NCAP(cap, cap)
#define NCAP(cap, name) ((props.cap) ? (#name " ") : "")

int main(int argc, char **argv)
{
    int ndevs = 0;
    if (cudaGetDeviceCount(&ndevs) != cudaSuccess)
        return 1;

    int gpuid = -1;
    if (argc > 1) {
        gpuid = atoi(argv[1]);
    }

    int version = 0;
    CUDA_CHECK(cudaDriverGetVersion(&version));
    std::cout << "Driver version: " << (version / 1000) << "."
              << ((version % 100) / 10) << std::endl;

    version = 0;
    CUDA_CHECK(cudaRuntimeGetVersion(&version));
    std::cout << "Runtime version: " << (version / 1000) << "."
              << ((version % 100) / 10) << std::endl;
    std::cout << std::endl;

    // Print information for each GPU
    for (int i = 0; i < ndevs; ++i)
    {
        // Skip GPUs
        if (gpuid >= 0 && i != gpuid) continue;

        CUDA_CHECK(cudaSetDevice(i));
        cudaDeviceProp props;
        CUDA_CHECK(cudaGetDeviceProperties(&props, i));

        std::cout << "GPU " << (i + 1) << ": " << props.name << " ("
                  << props.pciDomainID << "/" << props.pciBusID
                  << "/" << props.pciDeviceID << ")" << std::endl

                  << "Compute capability: sm_" << props.major << props.minor << std::endl
                  << "Global memory: " << (props.totalGlobalMem/1024.0/1024.0)
                  << " MB" << std::endl
                  << "Constant memory: " << props.totalConstMem
                  << " bytes" << std::endl
                  << "Shared memory: " << props.sharedMemPerBlock
                  << " bytes" << std::endl
                  << "Registers: " << props.regsPerBlock << std::endl
                  << "Warp size: " << props.warpSize << std::endl
                  << "Multiprocessors: " << props.multiProcessorCount
                  << std::endl
                  << "Copy engines: " << props.asyncEngineCount << std::endl
                  << "Clock rate: " << (props.clockRate / 1e6)
                  << " GHz" << std::endl
                  << "Threads per MP: " << props.maxThreadsPerMultiProcessor
                  << std::endl
                  << "Threads per block: " << props.maxThreadsPerBlock
                  << std::endl
                  << "Max block size: " << props.maxThreadsDim[0] << "x"
                  << props.maxThreadsDim[1] << "x" << props.maxThreadsDim[2]
                  << std::endl
                  << "Max grid size: " << props.maxGridSize[0] << "x"
                  << props.maxGridSize[1] << "x" << props.maxGridSize[2]
                  << std::endl
                  << "Pitch: " << props.memPitch << " bytes" << std::endl;

        std::cout << "Caps: " << NCAP(ECCEnabled, ecc)
                  << NCAP(deviceOverlap, overlap)
                  << NCAP(unifiedAddressing, uva)
                  << NCAP(kernelExecTimeoutEnabled, timeout)
                  << CAP(integrated) << NCAP(canMapHostMemory, hostdma)
                  << CAP(surfaceAlignment) << CAP(tccDriver) << std::endl;
        std::cout << std::endl;
    }

    std::cout << "DMA access: " << std::endl;
    int tmp = 0;

    // Print top row
    printf("   | ");
    for (int i = 0; i < ndevs; ++i)
        printf("%2d ", i + 1);
    printf("\n---+");
    for (int i = 0; i < ndevs; ++i)
        printf("---");
    printf("\n");

    for (int i = 0; i < ndevs; ++i)
    {
        printf("%2d | ", i + 1);
        for (int j = 0; j < ndevs; ++j)
        {
            if (i == j)
            {
                printf(" x ");
                continue;
            }

            cudaDeviceCanAccessPeer(&tmp, i, j);
            printf("%2d ", tmp ? 1 : 0);
        }
        printf("\n");
    }

    return 0;
}
<|endoftext|>