summaryrefslogtreecommitdiff
path: root/plugins/java-decompiler/engine/src/org/jetbrains/java/decompiler/modules/decompiler/vars/VarVersionsProcessor.java
blob: 06b7216c86faa5fcb92679be18a8583fc04f50e4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
/*
 * Copyright 2000-2014 JetBrains s.r.o.
 *
 * 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.
 */
package org.jetbrains.java.decompiler.modules.decompiler.vars;

import org.jetbrains.java.decompiler.code.CodeConstants;
import org.jetbrains.java.decompiler.main.DecompilerContext;
import org.jetbrains.java.decompiler.main.collectors.CounterContainer;
import org.jetbrains.java.decompiler.modules.decompiler.exps.ConstExprent;
import org.jetbrains.java.decompiler.modules.decompiler.exps.Exprent;
import org.jetbrains.java.decompiler.modules.decompiler.exps.VarExprent;
import org.jetbrains.java.decompiler.modules.decompiler.sforms.DirectGraph;
import org.jetbrains.java.decompiler.modules.decompiler.sforms.FlattenStatementsHelper;
import org.jetbrains.java.decompiler.modules.decompiler.sforms.SSAConstructorSparseEx;
import org.jetbrains.java.decompiler.modules.decompiler.stats.RootStatement;
import org.jetbrains.java.decompiler.struct.StructMethod;
import org.jetbrains.java.decompiler.struct.gen.VarType;
import org.jetbrains.java.decompiler.util.FastSparseSetFactory.FastSparseSet;

import java.util.*;
import java.util.Map.Entry;

public class VarVersionsProcessor {

  private HashMap<Integer, Integer> mapOriginalVarIndices = new HashMap<Integer, Integer>();

  private VarTypeProcessor typeproc;

  public void setVarVersions(RootStatement root) {

    StructMethod mt = (StructMethod)DecompilerContext.getProperty(DecompilerContext.CURRENT_METHOD);

    SSAConstructorSparseEx ssa = new SSAConstructorSparseEx();
    ssa.splitVariables(root, mt);

    FlattenStatementsHelper flatthelper = new FlattenStatementsHelper();
    DirectGraph dgraph = flatthelper.buildDirectGraph(root);

    //		System.out.println("~~~~~~~~~~~~~~~~~~~~~~ \r\n"+root.toJava());

    mergePhiVersions(ssa, dgraph);

    //		System.out.println("~~~~~~~~~~~~~~~~~~~~~~ \r\n"+root.toJava());

    typeproc = new VarTypeProcessor();
    typeproc.calculateVarTypes(root, dgraph);

    simpleMerge(typeproc, dgraph, mt);

    // FIXME: advanced merging

    eliminateNonJavaTypes(typeproc);

    setNewVarIndices(typeproc, dgraph);
  }

  private static void mergePhiVersions(SSAConstructorSparseEx ssa, DirectGraph dgraph) {

    // collect phi versions
    List<HashSet<VarVersionPaar>> lst = new ArrayList<HashSet<VarVersionPaar>>();
    for (Entry<VarVersionPaar, FastSparseSet<Integer>> ent : ssa.getPhi().entrySet()) {
      HashSet<VarVersionPaar> set = new HashSet<VarVersionPaar>();
      set.add(ent.getKey());
      for (Integer vers : ent.getValue()) {
        set.add(new VarVersionPaar(ent.getKey().var, vers.intValue()));
      }

      for (int i = lst.size() - 1; i >= 0; i--) {
        HashSet<VarVersionPaar> tset = lst.get(i);
        HashSet<VarVersionPaar> intersection = new HashSet<VarVersionPaar>(set);
        intersection.retainAll(tset);

        if (!intersection.isEmpty()) {
          set.addAll(tset);
          lst.remove(i);
        }
      }

      lst.add(set);
    }

    final HashMap<VarVersionPaar, Integer> phivers = new HashMap<VarVersionPaar, Integer>();
    for (HashSet<VarVersionPaar> set : lst) {
      int min = Integer.MAX_VALUE;
      for (VarVersionPaar paar : set) {
        if (paar.version < min) {
          min = paar.version;
        }
      }

      for (VarVersionPaar paar : set) {
        phivers.put(new VarVersionPaar(paar.var, paar.version), min);
      }
    }


    dgraph.iterateExprents(new DirectGraph.ExprentIterator() {
      public int processExprent(Exprent exprent) {
        List<Exprent> lst = exprent.getAllExprents(true);
        lst.add(exprent);

        for (Exprent expr : lst) {
          if (expr.type == Exprent.EXPRENT_VAR) {
            VarExprent var = (VarExprent)expr;
            Integer vers = phivers.get(new VarVersionPaar(var));
            if (vers != null) {
              var.setVersion(vers);
            }
          }
        }
        return 0;
      }
    });
  }

  private static void eliminateNonJavaTypes(VarTypeProcessor typeproc) {

    HashMap<VarVersionPaar, VarType> mapExprentMaxTypes = typeproc.getMapExprentMaxTypes();
    HashMap<VarVersionPaar, VarType> mapExprentMinTypes = typeproc.getMapExprentMinTypes();

    HashSet<VarVersionPaar> set = new HashSet<VarVersionPaar>(mapExprentMinTypes.keySet());
    for (VarVersionPaar paar : set) {
      VarType type = mapExprentMinTypes.get(paar);
      VarType maxtype = mapExprentMaxTypes.get(paar);

      if (type.type == CodeConstants.TYPE_BYTECHAR || type.type == CodeConstants.TYPE_SHORTCHAR) {
        if (maxtype != null && maxtype.type == CodeConstants.TYPE_CHAR) {
          type = VarType.VARTYPE_CHAR;
        }
        else {
          type = type.type == CodeConstants.TYPE_BYTECHAR ? VarType.VARTYPE_BYTE : VarType.VARTYPE_SHORT;
        }
        mapExprentMinTypes.put(paar, type);
        //} else if(type.type == CodeConstants.TYPE_CHAR && (maxtype == null || maxtype.type == CodeConstants.TYPE_INT)) { // when possible, lift char to int
        //	mapExprentMinTypes.put(paar, VarType.VARTYPE_INT);
      }
      else if (type.type == CodeConstants.TYPE_NULL) {
        mapExprentMinTypes.put(paar, VarType.VARTYPE_OBJECT);
      }
    }
  }

  private static void simpleMerge(VarTypeProcessor typeproc, DirectGraph dgraph, StructMethod mt) {

    HashMap<VarVersionPaar, VarType> mapExprentMaxTypes = typeproc.getMapExprentMaxTypes();
    HashMap<VarVersionPaar, VarType> mapExprentMinTypes = typeproc.getMapExprentMinTypes();

    HashMap<Integer, HashSet<Integer>> mapVarVersions = new HashMap<Integer, HashSet<Integer>>();

    for (VarVersionPaar varpaar : mapExprentMinTypes.keySet()) {
      if (varpaar.version >= 0) {  // don't merge constants
        HashSet<Integer> set = mapVarVersions.get(varpaar.var);
        if (set == null) {
          set = new HashSet<Integer>();
          mapVarVersions.put(varpaar.var, set);
        }
        set.add(varpaar.version);
      }
    }

    boolean is_method_static = mt.hasModifier(CodeConstants.ACC_STATIC);

    final HashMap<VarVersionPaar, Integer> mapMergedVersions = new HashMap<VarVersionPaar, Integer>();

    for (Entry<Integer, HashSet<Integer>> ent : mapVarVersions.entrySet()) {

      if (ent.getValue().size() > 1) {
        List<Integer> lstVersions = new ArrayList<Integer>(ent.getValue());
        Collections.sort(lstVersions);

        for (int i = 0; i < lstVersions.size(); i++) {
          VarVersionPaar firstpaar = new VarVersionPaar(ent.getKey(), lstVersions.get(i));
          VarType firsttype = mapExprentMinTypes.get(firstpaar);

          if (firstpaar.var == 0 && firstpaar.version == 1 && !is_method_static) {
            continue; // don't merge 'this' variable
          }

          for (int j = i + 1; j < lstVersions.size(); j++) {
            VarVersionPaar secpaar = new VarVersionPaar(ent.getKey(), lstVersions.get(j));
            VarType sectype = mapExprentMinTypes.get(secpaar);

            if (firsttype.equals(sectype) || (firsttype.equals(VarType.VARTYPE_NULL) && sectype.type == CodeConstants.TYPE_OBJECT)
                || (sectype.equals(VarType.VARTYPE_NULL) && firsttype.type == CodeConstants.TYPE_OBJECT)) {

              VarType firstMaxType = mapExprentMaxTypes.get(firstpaar);
              VarType secMaxType = mapExprentMaxTypes.get(secpaar);
              mapExprentMaxTypes.put(firstpaar, firstMaxType == null ? secMaxType :
                                                (secMaxType == null ? firstMaxType : VarType.getCommonMinType(firstMaxType, secMaxType)));


              mapMergedVersions.put(secpaar, firstpaar.version);
              mapExprentMaxTypes.remove(secpaar);
              mapExprentMinTypes.remove(secpaar);

              if (firsttype.equals(VarType.VARTYPE_NULL)) {
                mapExprentMinTypes.put(firstpaar, sectype);
                firsttype = sectype;
              }

              typeproc.getMapFinalVars().put(firstpaar, VarTypeProcessor.VAR_NONFINAL);

              lstVersions.remove(j);
              j--;
            }
          }
        }
      }
    }

    if (!mapMergedVersions.isEmpty()) {
      dgraph.iterateExprents(new DirectGraph.ExprentIterator() {
        public int processExprent(Exprent exprent) {
          List<Exprent> lst = exprent.getAllExprents(true);
          lst.add(exprent);

          for (Exprent expr : lst) {
            if (expr.type == Exprent.EXPRENT_VAR) {
              VarExprent varex = (VarExprent)expr;
              Integer newversion = mapMergedVersions.get(new VarVersionPaar(varex));
              if (newversion != null) {
                varex.setVersion(newversion);
              }
            }
          }

          return 0;
        }
      });
    }
  }

  private void setNewVarIndices(VarTypeProcessor typeproc, DirectGraph dgraph) {

    final HashMap<VarVersionPaar, VarType> mapExprentMaxTypes = typeproc.getMapExprentMaxTypes();
    HashMap<VarVersionPaar, VarType> mapExprentMinTypes = typeproc.getMapExprentMinTypes();
    HashMap<VarVersionPaar, Integer> mapFinalVars = typeproc.getMapFinalVars();

    CounterContainer ccon = DecompilerContext.getCounterContainer();

    final HashMap<VarVersionPaar, Integer> mapVarPaar = new HashMap<VarVersionPaar, Integer>();
    HashMap<Integer, Integer> mapOriginalVarIndices = new HashMap<Integer, Integer>();

    // map var-version paars on new var indexes
    HashSet<VarVersionPaar> set = new HashSet<VarVersionPaar>(mapExprentMinTypes.keySet());
    for (VarVersionPaar vpaar : set) {

      if (vpaar.version >= 0) {
        int newindex = vpaar.version == 1 ? vpaar.var :
                       ccon.getCounterAndIncrement(CounterContainer.VAR_COUNTER);

        VarVersionPaar newvar = new VarVersionPaar(newindex, 0);

        mapExprentMinTypes.put(newvar, mapExprentMinTypes.get(vpaar));
        mapExprentMaxTypes.put(newvar, mapExprentMaxTypes.get(vpaar));

        if (mapFinalVars.containsKey(vpaar)) {
          mapFinalVars.put(newvar, mapFinalVars.remove(vpaar));
        }

        mapVarPaar.put(vpaar, newindex);
        mapOriginalVarIndices.put(newindex, vpaar.var);
      }
    }

    // set new vars
    dgraph.iterateExprents(new DirectGraph.ExprentIterator() {
      public int processExprent(Exprent exprent) {
        List<Exprent> lst = exprent.getAllExprents(true);
        lst.add(exprent);

        for (Exprent expr : lst) {
          if (expr.type == Exprent.EXPRENT_VAR) {
            VarExprent varex = (VarExprent)expr;
            Integer newvarindex = mapVarPaar.get(new VarVersionPaar(varex));
            if (newvarindex != null) {
              varex.setIndex(newvarindex);
              varex.setVersion(0);
            }
          }
          else if (expr.type == Exprent.EXPRENT_CONST) {
            VarType maxType = mapExprentMaxTypes.get(new VarVersionPaar(expr.id, -1));
            if (maxType != null && maxType.equals(VarType.VARTYPE_CHAR)) {
              ((ConstExprent)expr).setConsttype(maxType);
            }
          }
        }

        return 0;
      }
    });

    this.mapOriginalVarIndices = mapOriginalVarIndices;
  }

  public VarType getVarType(VarVersionPaar varpaar) {
    return typeproc == null ? null : typeproc.getVarType(varpaar);
  }

  public void setVarType(VarVersionPaar varpaar, VarType type) {
    typeproc.setVarType(varpaar, type);
  }

  public int getVarFinal(VarVersionPaar varpaar) {

    int ret = VarTypeProcessor.VAR_FINAL;
    if (typeproc != null) {
      Integer fin = typeproc.getMapFinalVars().get(varpaar);
      ret = fin == null ? VarTypeProcessor.VAR_FINAL : fin.intValue();
    }

    return ret;
  }

  public void setVarFinal(VarVersionPaar varpaar, int finaltype) {
    typeproc.getMapFinalVars().put(varpaar, finaltype);
  }

  public HashMap<Integer, Integer> getMapOriginalVarIndices() {
    return mapOriginalVarIndices;
  }
}