int (@NotNull ControlFlow flow, final int sourceOffset, @NotNull List<? extends PsiElement> references) { class MyVisitor extends InstructionClientVisitor<Integer> { // set of exit points reached from this offset private final IntSet[] exitPoints = new IntOpenHashSet[flow.getSize()]; @Override public void visitInstruction(Instruction instruction, int offset, int nextOffset) { if (nextOffset > flow.getSize()) nextOffset = flow.getSize(); if (exitPoints[offset] == null) { exitPoints[offset] = new IntOpenHashSet(); } if (isLeaf(nextOffset)) { exitPoints[offset].add(offset); } else if (exitPoints[nextOffset] != null) { exitPoints[offset].addAll(exitPoints[nextOffset]); } } @Override @NotNull public Integer getResult() { int minOffset = flow.getSize(); int maxExitPoints = 0; nextOffset: for (int i = sourceOffset; i < exitPoints.length; i++) { IntSet exitPointSet = exitPoints[i]; final int size = exitPointSet == null ? 0 : exitPointSet.size(); if (size > maxExitPoints) { // this offset should be reachable from all other references for (PsiElement element : references) { final PsiElement statement = PsiUtil.getEnclosingStatement(element); if (statement == null) continue; final int endOffset = flow.getEndOffset(statement); if (endOffset == -1) continue; if (i != endOffset && !isInstructionReachable(flow, i, endOffset)) continue nextOffset; } minOffset = i; maxExitPoints = size; } } return minOffset; } } MyVisitor visitor = new MyVisitor(); depthFirstSearch(flow, visitor); return visitor.getResult().intValue(); }