private static void findRemovableSelfJoins(RelMetadataQuery mq, HiveLoptMultiJoin multiJoin) {
    // Candidates for self-joins must be simple factors
    Map<Integer, RelOptTable> simpleFactors = getSimpleFactors(mq, multiJoin);

    // See if a simple factor is repeated and therefore potentially is
    // part of a self-join.  Restrict each factor to at most one
    // self-join.
    final List<RelOptTable> repeatedTables = new ArrayList<>();
    final Map<Integer, Integer> selfJoinPairs = new HashMap<>();
    @KeyFor("simpleFactors") Integer [] factors =
            new TreeSet<>(simpleFactors.keySet()).toArray(new Integer[0]);
    for (int i = 0; i < factors.length; i++) {
      if (repeatedTables.contains(simpleFactors.get(factors[i]))) {
        continue;
      }
      for (int j = i + 1; j < factors.length; j++) {
        @KeyFor("simpleFactors") int leftFactor = factors[i];
        @KeyFor("simpleFactors") int rightFactor = factors[j];
        if (simpleFactors.get(leftFactor).getQualifiedName().equals(
                simpleFactors.get(rightFactor).getQualifiedName())) {
          selfJoinPairs.put(leftFactor, rightFactor);
          repeatedTables.add(simpleFactors.get(leftFactor));
          break;
        }
      }
    }

    // From the candidate self-join pairs, determine if there is
    // the appropriate join condition between the two factors that will
    // allow the join to be removed.
    for (Integer factor1 : selfJoinPairs.keySet()) {
      final int factor2 = selfJoinPairs.get(factor1);
      final List<RexNode> selfJoinFilters = new ArrayList<>();
      for (RexNode filter : multiJoin.getJoinFilters()) {
        ImmutableBitSet joinFactors =
                multiJoin.getFactorsRefByJoinFilter(filter);
        if ((joinFactors.cardinality() == 2)
                && joinFactors.get(factor1)
                && joinFactors.get(factor2)) {
          selfJoinFilters.add(filter);
        }
      }
      if ((selfJoinFilters.size() > 0)
              && isSelfJoinFilterUnique(
              mq,
              multiJoin,
              factor1,
              factor2,
              selfJoinFilters)) {
        multiJoin.addRemovableSelfJoinPair(factor1, factor2);
      }
    }
  }
Locates pairs of joins that are self-joins where the join can be removed
because the join condition between the two factors is an equality join on
unique keys.

@param multiJoin join factors being optimized
ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/rules/HiveLoptOptimizeJoinRule.java