repo
stringlengths
1
191
file
stringlengths
23
351
code
stringlengths
0
5.32M
file_length
int64
0
5.32M
avg_line_length
float64
0
2.9k
max_line_length
int64
0
288k
extension_type
stringclasses
1 value
WALA
WALA-master/cast/src/main/java/com/ibm/wala/cast/ipa/callgraph/CrossLanguageInstanceKeys.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.cast.ipa.callgraph; import com.ibm.wala.classLoader.NewSiteReference; import com.ibm.wala.classLoader.ProgramCounter; import com.ibm.wala.core.util.strings.Atom; import com.ibm.wala.ipa.callgraph.CGNode; import com.ibm.wala.ipa.callgraph.propagation.InstanceKey; import com.ibm.wala.ipa.callgraph.propagation.InstanceKeyFactory; import com.ibm.wala.types.TypeReference; import java.util.Map; /** * An InstanceKeyFactory implementation that is designed to support multiple languages. This * implementation delegates to one of several child instance key factories based on the language * associated with the IClass or TypeReference for which an instance key is being chosen. * * @author Julian Dolby (dolby@us.ibm.com) */ public class CrossLanguageInstanceKeys implements InstanceKeyFactory { private final Map<Atom, InstanceKeyFactory> languageSelectors; public CrossLanguageInstanceKeys(Map<Atom, InstanceKeyFactory> languageSelectors) { this.languageSelectors = languageSelectors; } private static Atom getLanguage(TypeReference type) { return type.getClassLoader().getLanguage(); } private static Atom getLanguage(NewSiteReference site) { return getLanguage(site.getDeclaredType()); } // private static Atom getLanguage(CGNode node) { // return getLanguage(node.getMethod().getDeclaringClass().getReference()); // } private InstanceKeyFactory getSelector(NewSiteReference site) { return languageSelectors.get(getLanguage(site)); } private InstanceKeyFactory getSelector(TypeReference type) { return languageSelectors.get(getLanguage(type)); } @Override public InstanceKey getInstanceKeyForAllocation(CGNode node, NewSiteReference allocation) { return getSelector(allocation).getInstanceKeyForAllocation(node, allocation); } @Override public InstanceKey getInstanceKeyForMultiNewArray( CGNode node, NewSiteReference allocation, int dim) { return getSelector(allocation).getInstanceKeyForMultiNewArray(node, allocation, dim); } @Override public InstanceKey getInstanceKeyForConstant(TypeReference type, Object S) { return getSelector(type).getInstanceKeyForConstant(type, S); } @Override public InstanceKey getInstanceKeyForPEI(CGNode node, ProgramCounter instr, TypeReference type) { assert getSelector(type) != null : "no instance keys for " + type; return getSelector(type).getInstanceKeyForPEI(node, instr, type); } @Override public InstanceKey getInstanceKeyForMetadataObject(Object obj, TypeReference objType) { return getSelector(objType).getInstanceKeyForMetadataObject(obj, objType); } }
3,026
35.035714
98
java
WALA
WALA-master/cast/src/main/java/com/ibm/wala/cast/ipa/callgraph/CrossLanguageMethodTargetSelector.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.cast.ipa.callgraph; import com.ibm.wala.classLoader.CallSiteReference; import com.ibm.wala.classLoader.IClass; import com.ibm.wala.classLoader.IMethod; import com.ibm.wala.core.util.strings.Atom; import com.ibm.wala.ipa.callgraph.CGNode; import com.ibm.wala.ipa.callgraph.MethodTargetSelector; import com.ibm.wala.types.MethodReference; import java.util.Map; /** * A MethodTargetSelector implementation that supports multiple languages. It works by delegating to * a language-specific child selector based on the language associated with the MethodReference for * which a target is being chosen. * * <p>This provides a simple way to combine language-specific target selection policies---such as * those used for constructor calls in JavaScript and for bean methods in J2EE. * * @author Julian Dolby (dolby@us.ibm.com) */ public class CrossLanguageMethodTargetSelector implements MethodTargetSelector { private final Map<Atom, MethodTargetSelector> languageSelectors; public CrossLanguageMethodTargetSelector(Map<Atom, MethodTargetSelector> languageSelectors) { this.languageSelectors = languageSelectors; } private static Atom getLanguage(MethodReference target) { return target.getDeclaringClass().getClassLoader().getLanguage(); } private static Atom getLanguage(CallSiteReference site) { return getLanguage(site.getDeclaredTarget()); } private MethodTargetSelector getSelector(CallSiteReference site) { return languageSelectors.get(getLanguage(site)); } @Override public IMethod getCalleeTarget(CGNode caller, CallSiteReference site, IClass receiver) { assert getSelector(site) != null : "no selector for " + getLanguage(site) + " method " + site; return getSelector(site).getCalleeTarget(caller, site, receiver); } }
2,182
36.637931
100
java
WALA
WALA-master/cast/src/main/java/com/ibm/wala/cast/ipa/callgraph/CrossLanguageSSAPropagationCallGraphBuilder.java
/* * Copyright (c) 2013 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.cast.ipa.callgraph; import com.ibm.wala.cast.ipa.callgraph.AstSSAPropagationCallGraphBuilder.AstPointerAnalysisImpl.AstImplicitPointsToSetVisitor; import com.ibm.wala.cast.util.TargetLanguageSelector; import com.ibm.wala.classLoader.IMethod; import com.ibm.wala.core.util.strings.Atom; import com.ibm.wala.ipa.callgraph.AnalysisOptions; import com.ibm.wala.ipa.callgraph.CGNode; import com.ibm.wala.ipa.callgraph.CallGraph; import com.ibm.wala.ipa.callgraph.IAnalysisCacheView; import com.ibm.wala.ipa.callgraph.impl.AbstractRootMethod; import com.ibm.wala.ipa.callgraph.impl.ExplicitCallGraph; import com.ibm.wala.ipa.callgraph.propagation.InstanceKey; import com.ibm.wala.ipa.callgraph.propagation.InstanceKeyFactory; import com.ibm.wala.ipa.callgraph.propagation.LocalPointerKey; import com.ibm.wala.ipa.callgraph.propagation.PointerAnalysis; import com.ibm.wala.ipa.callgraph.propagation.PointerKeyFactory; import com.ibm.wala.ipa.callgraph.propagation.PointsToMap; import com.ibm.wala.ipa.callgraph.propagation.PropagationCallGraphBuilder; import com.ibm.wala.ipa.callgraph.propagation.PropagationSystem; import com.ibm.wala.util.intset.MutableMapping; public abstract class CrossLanguageSSAPropagationCallGraphBuilder extends AstSSAPropagationCallGraphBuilder { private final TargetLanguageSelector<ConstraintVisitor, CGNode> visitors; private final TargetLanguageSelector<InterestingVisitor, Integer> interesting; protected abstract TargetLanguageSelector<ConstraintVisitor, CGNode> makeMainVisitorSelector(); protected abstract TargetLanguageSelector<InterestingVisitor, Integer> makeInterestingVisitorSelector(); protected abstract TargetLanguageSelector<AstImplicitPointsToSetVisitor, LocalPointerKey> makeImplicitVisitorSelector(CrossLanguagePointerAnalysisImpl analysis); protected abstract TargetLanguageSelector<AbstractRootMethod, CrossLanguageCallGraph> makeRootNodeSelector(); protected CrossLanguageSSAPropagationCallGraphBuilder( IMethod fakeRootClass, AnalysisOptions options, IAnalysisCacheView cache, PointerKeyFactory pointerKeyFactory) { super(fakeRootClass, options, cache, pointerKeyFactory); visitors = makeMainVisitorSelector(); interesting = makeInterestingVisitorSelector(); } @Override protected ExplicitCallGraph createEmptyCallGraph(IMethod fakeRootClass, AnalysisOptions options) { return new CrossLanguageCallGraph( makeRootNodeSelector(), fakeRootClass, options, getAnalysisCache()); } protected static Atom getLanguage(CGNode node) { return node.getMethod().getReference().getDeclaringClass().getClassLoader().getLanguage(); } @Override protected InterestingVisitor makeInterestingVisitor(CGNode node, int vn) { return interesting.get(getLanguage(node), vn); } @Override public ConstraintVisitor makeVisitor(CGNode node) { return visitors.get(getLanguage(node), node); } @Override protected PropagationSystem makeSystem(AnalysisOptions options) { return new PropagationSystem(callGraph, pointerKeyFactory, instanceKeyFactory) { @Override public PointerAnalysis<InstanceKey> makePointerAnalysis(PropagationCallGraphBuilder builder) { assert builder == CrossLanguageSSAPropagationCallGraphBuilder.this; return new CrossLanguagePointerAnalysisImpl( CrossLanguageSSAPropagationCallGraphBuilder.this, cg, pointsToMap, instanceKeys, pointerKeyFactory, instanceKeyFactory); } }; } protected static class CrossLanguagePointerAnalysisImpl extends AstPointerAnalysisImpl { private final TargetLanguageSelector<AstImplicitPointsToSetVisitor, LocalPointerKey> implicitVisitors; protected CrossLanguagePointerAnalysisImpl( CrossLanguageSSAPropagationCallGraphBuilder builder, CallGraph cg, PointsToMap pointsToMap, MutableMapping<InstanceKey> instanceKeys, PointerKeyFactory pointerKeys, InstanceKeyFactory iKeyFactory) { super(builder, cg, pointsToMap, instanceKeys, pointerKeys, iKeyFactory); this.implicitVisitors = builder.makeImplicitVisitorSelector(this); } @Override protected ImplicitPointsToSetVisitor makeImplicitPointsToVisitor(LocalPointerKey lpk) { return implicitVisitors.get(getLanguage(lpk.getNode()), lpk); } } @Override protected void customInit() { for (CGNode root : callGraph) { markDiscovered(root); } } }
4,921
38.063492
126
java
WALA
WALA-master/cast/src/main/java/com/ibm/wala/cast/ipa/callgraph/DelegatingAstPointerKeys.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.cast.ipa.callgraph; import com.ibm.wala.classLoader.IClass; import com.ibm.wala.classLoader.IField; import com.ibm.wala.core.util.strings.Atom; import com.ibm.wala.ipa.callgraph.CGNode; import com.ibm.wala.ipa.callgraph.propagation.ConcreteTypeKey; import com.ibm.wala.ipa.callgraph.propagation.ConstantKey; import com.ibm.wala.ipa.callgraph.propagation.FilteredPointerKey; import com.ibm.wala.ipa.callgraph.propagation.InstanceFieldKey; import com.ibm.wala.ipa.callgraph.propagation.InstanceKey; import com.ibm.wala.ipa.callgraph.propagation.PointerKey; import com.ibm.wala.ipa.callgraph.propagation.PointerKeyFactory; import com.ibm.wala.util.collections.NonNullSingletonIterator; import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class DelegatingAstPointerKeys implements AstPointerKeyFactory { private final PointerKeyFactory base; public DelegatingAstPointerKeys(PointerKeyFactory base) { this.base = base; } @Override public PointerKey getPointerKeyForLocal(CGNode node, int valueNumber) { return base.getPointerKeyForLocal(node, valueNumber); } @Override public FilteredPointerKey getFilteredPointerKeyForLocal( CGNode node, int valueNumber, FilteredPointerKey.TypeFilter filter) { return base.getFilteredPointerKeyForLocal(node, valueNumber, filter); } @Override public PointerKey getPointerKeyForReturnValue(CGNode node) { return base.getPointerKeyForReturnValue(node); } @Override public PointerKey getPointerKeyForExceptionalReturnValue(CGNode node) { return base.getPointerKeyForExceptionalReturnValue(node); } @Override public PointerKey getPointerKeyForStaticField(IField f) { return base.getPointerKeyForStaticField(f); } @Override public PointerKey getPointerKeyForObjectCatalog(InstanceKey I) { return new ObjectPropertyCatalogKey(I); } @Override public PointerKey getPointerKeyForInstanceField(InstanceKey I, IField f) { return base.getPointerKeyForInstanceField(I, f); } @Override public PointerKey getPointerKeyForArrayContents(InstanceKey I) { return base.getPointerKeyForArrayContents(I); } @Override public Iterator<PointerKey> getPointerKeysForReflectedFieldWrite(InstanceKey I, InstanceKey F) { List<PointerKey> result = new ArrayList<>(); if (F instanceof ConstantKey) { PointerKey ifk = getInstanceFieldPointerKeyForConstant(I, (ConstantKey<?>) F); if (ifk != null) { result.add(ifk); } } result.add(ReflectedFieldPointerKey.mapped(new ConcreteTypeKey(getFieldNameType(F)), I)); return result.iterator(); } /** get type for F appropriate for use in a field name. */ protected IClass getFieldNameType(InstanceKey F) { return F.getConcreteType(); } /** * if F is a supported constant representing a field, return the corresponding {@link * InstanceFieldKey} for I. Otherwise, return {@code null}. */ protected PointerKey getInstanceFieldPointerKeyForConstant(InstanceKey I, ConstantKey<?> F) { Object v = F.getValue(); // FIXME: current only constant string are handled if (I.getConcreteType().getClassLoader().getLanguage().modelConstant(v)) { IField f = I.getConcreteType().getField(Atom.findOrCreateUnicodeAtom(String.valueOf(v))); if (f != null) { return getPointerKeyForInstanceField(I, f); } } return null; } @Override public Iterator<PointerKey> getPointerKeysForReflectedFieldRead(InstanceKey I, InstanceKey F) { if (F instanceof ConstantKey) { PointerKey ifk = getInstanceFieldPointerKeyForConstant(I, (ConstantKey<?>) F); if (ifk != null) { return new NonNullSingletonIterator<>(ifk); } } PointerKey x = ReflectedFieldPointerKey.mapped(new ConcreteTypeKey(getFieldNameType(F)), I); return new NonNullSingletonIterator<>(x); } }
4,279
32.968254
98
java
WALA
WALA-master/cast/src/main/java/com/ibm/wala/cast/ipa/callgraph/GlobalObjectKey.java
/* * Copyright (c) 2013 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.cast.ipa.callgraph; import com.ibm.wala.classLoader.IClass; import com.ibm.wala.classLoader.NewSiteReference; import com.ibm.wala.ipa.callgraph.CGNode; import com.ibm.wala.ipa.callgraph.CallGraph; import com.ibm.wala.ipa.callgraph.propagation.InstanceKey; import com.ibm.wala.util.collections.EmptyIterator; import com.ibm.wala.util.collections.Pair; import java.util.Iterator; /** * Represents the JavaScript global object. * * @see com.ibm.wala.cast.js.ipa.callgraph.JSSSAPropagationCallGraphBuilder */ @SuppressWarnings({"javadoc", "JavadocReference"}) public class GlobalObjectKey implements InstanceKey { private final IClass concreteType; public GlobalObjectKey(IClass concreteType) { this.concreteType = concreteType; } @Override public IClass getConcreteType() { return concreteType; } @Override public String toString() { return "Global Object"; } @Override public Iterator<Pair<CGNode, NewSiteReference>> getCreationSites(CallGraph CG) { return EmptyIterator.instance(); } }
1,425
26.960784
82
java
WALA
WALA-master/cast/src/main/java/com/ibm/wala/cast/ipa/callgraph/MiscellaneousHacksContextSelector.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.cast.ipa.callgraph; import com.ibm.wala.classLoader.CallSiteReference; import com.ibm.wala.classLoader.IClass; import com.ibm.wala.classLoader.IClassLoader; import com.ibm.wala.classLoader.IMethod; import com.ibm.wala.classLoader.Language; import com.ibm.wala.core.util.strings.Atom; import com.ibm.wala.ipa.callgraph.CGNode; import com.ibm.wala.ipa.callgraph.Context; import com.ibm.wala.ipa.callgraph.ContextSelector; import com.ibm.wala.ipa.callgraph.propagation.InstanceKey; import com.ibm.wala.ipa.cha.IClassHierarchy; import com.ibm.wala.types.ClassLoaderReference; import com.ibm.wala.types.Descriptor; import com.ibm.wala.types.MethodReference; import com.ibm.wala.types.TypeName; import com.ibm.wala.types.TypeReference; import com.ibm.wala.util.collections.HashSetFactory; import com.ibm.wala.util.debug.Assertions; import com.ibm.wala.util.intset.IntSet; import java.util.Set; public class MiscellaneousHacksContextSelector implements ContextSelector { private final Set<MethodReference> methodsToSpecialize; private final ContextSelector specialPolicy; private final ContextSelector basePolicy; public MiscellaneousHacksContextSelector( ContextSelector special, ContextSelector base, IClassHierarchy cha, String[][] descriptors) { basePolicy = base; specialPolicy = special; methodsToSpecialize = HashSetFactory.make(); for (String[] descr : descriptors) { switch (descr.length) { // loader name, loader language, classname, method name, method descr case 5: { ClassLoaderReference clr = cha.getScope().getLoader(Atom.findOrCreateUnicodeAtom(descr[0])); IClassLoader loader = cha.getLoader(clr); MethodReference ref = MethodReference.findOrCreate( TypeReference.findOrCreate(clr, TypeName.string2TypeName(descr[2])), Atom.findOrCreateUnicodeAtom(descr[3]), Descriptor.findOrCreateUTF8(loader.getLanguage(), descr[4])); if (cha.resolveMethod(ref) != null) { methodsToSpecialize.add(cha.resolveMethod(ref).getReference()); } else { methodsToSpecialize.add(ref); } break; } // classname, method name, method descr case 3: { MethodReference ref = MethodReference.findOrCreate( TypeReference.findOrCreate( ClassLoaderReference.Application, TypeName.string2TypeName(descr[0])), Atom.findOrCreateUnicodeAtom(descr[1]), Descriptor.findOrCreateUTF8(Language.JAVA, descr[2])); methodsToSpecialize.add(cha.resolveMethod(ref).getReference()); break; } // loader name, classname, meaning all methods of that class case 2: { IClass klass = cha.lookupClass( TypeReference.findOrCreate( new ClassLoaderReference( Atom.findOrCreateUnicodeAtom(descr[0]), ClassLoaderReference.Java, null), TypeName.string2TypeName(descr[1]))); for (IMethod M : klass.getDeclaredMethods()) { methodsToSpecialize.add(M.getReference()); } break; } // classname, meaning all methods of that class case 1: { IClass klass = cha.lookupClass( TypeReference.findOrCreate( ClassLoaderReference.Application, TypeName.string2TypeName(descr[0]))); for (IMethod M : klass.getDeclaredMethods()) { methodsToSpecialize.add(M.getReference()); } break; } default: Assertions.UNREACHABLE(); } } System.err.println(("hacking context selector for methods " + methodsToSpecialize)); } @Override public Context getCalleeTarget( CGNode caller, CallSiteReference site, IMethod callee, InstanceKey[] receiver) { if (methodsToSpecialize.contains(site.getDeclaredTarget()) || methodsToSpecialize.contains(callee.getReference())) { return specialPolicy.getCalleeTarget(caller, site, callee, receiver); } else { return basePolicy.getCalleeTarget(caller, site, callee, receiver); } } @Override public IntSet getRelevantParameters(CGNode caller, CallSiteReference site) { return specialPolicy .getRelevantParameters(caller, site) .union(basePolicy.getRelevantParameters(caller, site)); } }
5,134
34.659722
99
java
WALA
WALA-master/cast/src/main/java/com/ibm/wala/cast/ipa/callgraph/ObjectPropertyCatalogKey.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.cast.ipa.callgraph; import com.ibm.wala.ipa.callgraph.propagation.AbstractPointerKey; import com.ibm.wala.ipa.callgraph.propagation.InstanceKey; public class ObjectPropertyCatalogKey extends AbstractPointerKey { private final InstanceKey object; public String getName() { return "catalog of " + object.toString(); } public ObjectPropertyCatalogKey(InstanceKey object) { this.object = object; } @Override public boolean equals(Object x) { return (x instanceof ObjectPropertyCatalogKey) && ((ObjectPropertyCatalogKey) x).object.equals(object); } @Override public int hashCode() { return object.hashCode(); } @Override public String toString() { return '[' + getName() + ']'; } public InstanceKey getObject() { return object; } }
1,195
24.446809
72
java
WALA
WALA-master/cast/src/main/java/com/ibm/wala/cast/ipa/callgraph/OneLevelForLexicalAccessFunctions.java
/* * Copyright (c) 2013 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.cast.ipa.callgraph; import com.ibm.wala.cast.ipa.callgraph.ScopeMappingInstanceKeys.ScopeMappingInstanceKey; import com.ibm.wala.classLoader.CallSiteReference; import com.ibm.wala.classLoader.IMethod; import com.ibm.wala.ipa.callgraph.CGNode; import com.ibm.wala.ipa.callgraph.Context; import com.ibm.wala.ipa.callgraph.ContextSelector; import com.ibm.wala.ipa.callgraph.propagation.InstanceKey; import com.ibm.wala.util.intset.IntSet; import com.ibm.wala.util.intset.IntSetUtil; /** * Adds one-level of {@link ArgumentInstanceContext} on the function argument for functions that * perform lexical accesses (i.e., those functions represented by a {@link * ScopeMappingInstanceKey}). In essence, this guarantees that when a function is cloned according * to some {@link ContextSelector}, its nested functions that may do lexical accesses if its * variables have corresponding clones. */ public class OneLevelForLexicalAccessFunctions implements ContextSelector { private final ContextSelector baseSelector; public OneLevelForLexicalAccessFunctions(ContextSelector baseSelector) { this.baseSelector = baseSelector; } @Override public Context getCalleeTarget( CGNode caller, CallSiteReference site, IMethod callee, InstanceKey[] receiver) { final Context base = baseSelector.getCalleeTarget(caller, site, callee, receiver); if (receiver != null && receiver[0] != null && receiver[0] instanceof ScopeMappingInstanceKey) { final ScopeMappingInstanceKey smik = (ScopeMappingInstanceKey) receiver[0]; return new ArgumentInstanceContext(base, 0, smik); } else { return base; } } @Override public IntSet getRelevantParameters(CGNode caller, CallSiteReference site) { return IntSetUtil.make(new int[] {0}).union(baseSelector.getRelevantParameters(caller, site)); } }
2,224
39.454545
100
java
WALA
WALA-master/cast/src/main/java/com/ibm/wala/cast/ipa/callgraph/ReflectedFieldPointerKey.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.cast.ipa.callgraph; import com.ibm.wala.ipa.callgraph.propagation.AbstractFieldPointerKey; import com.ibm.wala.ipa.callgraph.propagation.InstanceKey; public abstract class ReflectedFieldPointerKey extends AbstractFieldPointerKey { ReflectedFieldPointerKey(InstanceKey container) { super(container); } public abstract Object getFieldIdentifier(); private static final Object arrayStateKey = new Object() { @Override public String toString() { return "ArrayStateKey"; } }; @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (obj instanceof ReflectedFieldPointerKey) { ReflectedFieldPointerKey other = (ReflectedFieldPointerKey) obj; return getFieldIdentifier().equals(other.getFieldIdentifier()) && getInstanceKey().equals(other.getInstanceKey()); } else { return false; } } @Override public int hashCode() { return getFieldIdentifier().hashCode() ^ getInstanceKey().hashCode(); } @Override public String toString() { return "[" + getInstanceKey() + "; " + getFieldIdentifier() + ']'; } public static ReflectedFieldPointerKey literal(final String lit, InstanceKey instance) { return new ReflectedFieldPointerKey(instance) { @Override public Object getFieldIdentifier() { return lit; } }; } public static ReflectedFieldPointerKey mapped(final InstanceKey mapFrom, InstanceKey instance) { return new ReflectedFieldPointerKey(instance) { @Override public Object getFieldIdentifier() { return mapFrom; } }; } public static ReflectedFieldPointerKey index(InstanceKey instance) { return new ReflectedFieldPointerKey(instance) { @Override public Object getFieldIdentifier() { return arrayStateKey; } }; } }
2,289
26.590361
98
java
WALA
WALA-master/cast/src/main/java/com/ibm/wala/cast/ipa/callgraph/ScopeMappingInstanceKeys.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.cast.ipa.callgraph; import com.ibm.wala.classLoader.IClass; import com.ibm.wala.classLoader.NewSiteReference; import com.ibm.wala.classLoader.ProgramCounter; import com.ibm.wala.ipa.callgraph.CGNode; import com.ibm.wala.ipa.callgraph.CallGraph; import com.ibm.wala.ipa.callgraph.propagation.InstanceKey; import com.ibm.wala.ipa.callgraph.propagation.InstanceKeyFactory; import com.ibm.wala.ipa.callgraph.propagation.PointerKey; import com.ibm.wala.ipa.callgraph.propagation.PropagationCallGraphBuilder; import com.ibm.wala.types.TypeReference; import com.ibm.wala.util.collections.CompoundIterator; import com.ibm.wala.util.collections.EmptyIterator; import com.ibm.wala.util.collections.FilterIterator; import com.ibm.wala.util.collections.NonNullSingletonIterator; import com.ibm.wala.util.collections.Pair; import java.util.Collection; import java.util.Iterator; /** * An {@link InstanceKeyFactory} that returns {@link ScopeMappingInstanceKey}s as necessary to * handle interprocedural lexical scoping (specifically, to handle closure creation when a function * escapes its allocating scope) */ public abstract class ScopeMappingInstanceKeys implements InstanceKeyFactory { /** * does base require a scope mapping key? Typically, true if base is allocated in a nested lexical * scope, to handle the case of base being a function that performs closure accesses */ protected abstract boolean needsScopeMappingKey(InstanceKey base); protected final PropagationCallGraphBuilder builder; private final InstanceKeyFactory basic; /** * An {@link InstanceKey} carrying information about which {@link CGNode}s represent lexical * parents of the allocating {@link CGNode}. * * <p>The fact that we discover at most one {@link CGNode} per lexical parent relies on the * following property: in a call graph, the contexts used for a nested function can be finer than * those used for the containing function, but _not_ coarser. This ensures that there is at most * one CGNode corresponding to a lexical parent (e.g., we don't get two clones of function f1() * invoking a single CGNode representing nested function f2()) * * <p>Note that it is possible to not find a {@link CGNode} corresponding to some lexical parent; * this occurs when a deeply nested function is returned before being invoked, so some lexical * parent is no longer on the call stack when the function is allocated. See test case nested.js. */ public class ScopeMappingInstanceKey implements InstanceKey { /** the underlying instance key */ private final InstanceKey base; /** the node in which base is allocated */ private final CGNode creator; public ScopeMappingInstanceKey(CGNode creator, InstanceKey base) { this.creator = creator; this.base = base; } @Override public IClass getConcreteType() { return base.getConcreteType(); } /** get the CGNode representing the lexical parent of {@link #creator} with name definer */ public Iterator<CGNode> getFunargNodes(Pair<String, String> name) { Collection<CGNode> constructorCallers = getConstructorCallers(this, name); assert constructorCallers != null && !constructorCallers.isEmpty() : "no callers for constructor"; Iterator<CGNode> result = EmptyIterator.instance(); for (CGNode callerOfConstructor : constructorCallers) { if (callerOfConstructor .getMethod() .getReference() .getDeclaringClass() .getName() .toString() .equals(name.snd)) { result = new CompoundIterator<>(result, new NonNullSingletonIterator<>(callerOfConstructor)); } else { PointerKey funcKey = builder.getPointerKeyForLocal(callerOfConstructor, 1); for (InstanceKey funcPtr : builder.getPointerAnalysis().getPointsToSet(funcKey)) { if (funcPtr != this && funcPtr instanceof ScopeMappingInstanceKey) { result = new CompoundIterator<>( result, ((ScopeMappingInstanceKey) funcPtr).getFunargNodes(name)); } } } } return result; } @Override public int hashCode() { return base.hashCode() * creator.hashCode(); } @Override public boolean equals(Object o) { return (o instanceof ScopeMappingInstanceKey) && ((ScopeMappingInstanceKey) o).base.equals(base) && ((ScopeMappingInstanceKey) o).creator.equals(creator); } @Override public String toString() { return "SMIK:" + base + "@creator:" + creator; } public InstanceKey getBase() { return base; } public CGNode getCreator() { return creator; } @Override public Iterator<Pair<CGNode, NewSiteReference>> getCreationSites(CallGraph CG) { return new FilterIterator<>(base.getCreationSites(CG), o -> o.fst.equals(creator)); } } @Override public InstanceKey getInstanceKeyForAllocation( CGNode creatorNode, NewSiteReference allocationSite) { InstanceKey base = basic.getInstanceKeyForAllocation(creatorNode, allocationSite); if (base != null && needsScopeMappingKey(base)) { return new ScopeMappingInstanceKey(creatorNode, base); } else { return base; } } /** get the CGNodes corresponding to the method that invoked the constructor for smik */ protected abstract Collection<CGNode> getConstructorCallers( ScopeMappingInstanceKey smik, Pair<String, String> name); @Override public InstanceKey getInstanceKeyForMultiNewArray( CGNode node, NewSiteReference allocation, int dim) { return basic.getInstanceKeyForMultiNewArray(node, allocation, dim); } @Override public InstanceKey getInstanceKeyForConstant(TypeReference type, Object S) { return basic.getInstanceKeyForConstant(type, S); } @Override public InstanceKey getInstanceKeyForPEI(CGNode node, ProgramCounter instr, TypeReference type) { return basic.getInstanceKeyForPEI(node, instr, type); } @Override public InstanceKey getInstanceKeyForMetadataObject(Object obj, TypeReference objType) { return basic.getInstanceKeyForMetadataObject(obj, objType); } public ScopeMappingInstanceKeys(PropagationCallGraphBuilder builder, InstanceKeyFactory basic) { this.basic = basic; this.builder = builder; } }
6,826
36.718232
100
java
WALA
WALA-master/cast/src/main/java/com/ibm/wala/cast/ipa/callgraph/ScriptEntryPoints.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.cast.ipa.callgraph; import com.ibm.wala.cast.ipa.callgraph.AstCallGraph.ScriptFakeRoot; import com.ibm.wala.classLoader.CallSiteReference; import com.ibm.wala.classLoader.IClass; import com.ibm.wala.classLoader.IMethod; import com.ibm.wala.ipa.callgraph.Entrypoint; import com.ibm.wala.ipa.callgraph.impl.AbstractRootMethod; import com.ibm.wala.ipa.cha.IClassHierarchy; import com.ibm.wala.ssa.SSAAbstractInvokeInstruction; import com.ibm.wala.types.TypeReference; import com.ibm.wala.util.collections.HashSetFactory; import java.util.Iterator; import java.util.Set; public abstract class ScriptEntryPoints implements Iterable<Entrypoint> { protected final IClassHierarchy cha; protected final IClass scriptType; public class ScriptEntryPoint extends Entrypoint { public ScriptEntryPoint(IMethod scriptCodeBody) { super(scriptCodeBody); } @Override public CallSiteReference makeSite(int programCounter) { return makeScriptSite(getMethod(), programCounter); } @Override public TypeReference[] getParameterTypes(int i) { assert i == 0; if (getMethod().isStatic()) { return new TypeReference[0]; } else { return new TypeReference[] {getMethod().getDeclaringClass().getReference()}; } } @Override public int getNumberOfParameters() { return getMethod().isStatic() ? 0 : 1; } @Override public SSAAbstractInvokeInstruction addCall(AbstractRootMethod m) { CallSiteReference site = makeSite(0); if (site == null) { return null; } int functionVn = getMethod().isStatic() ? -1 : makeArgument(m, 0); int paramVns[] = new int[Math.max(0, getNumberOfParameters() - 1)]; for (int j = 0; j < paramVns.length; j++) { paramVns[j] = makeArgument(m, j + 1); } return ((ScriptFakeRoot) m).addDirectCall(functionVn, paramVns, site); } } public ScriptEntryPoints(IClassHierarchy cha, IClass scriptType) { this.cha = cha; this.scriptType = scriptType; } protected abstract CallSiteReference makeScriptSite(IMethod m, int pc); protected boolean keep() { return true; } @Override public Iterator<Entrypoint> iterator() { Set<Entrypoint> ES = HashSetFactory.make(); Iterator<IClass> classes = scriptType.getClassLoader().iterateAllClasses(); while (classes.hasNext()) { IClass cls = classes.next(); if (cha.isSubclassOf(cls, scriptType) && !cls.isAbstract()) { for (IMethod method : cls.getDeclaredMethods()) { if (keep()) { ES.add(new ScriptEntryPoint(method)); } } } } return ES.iterator(); } public Entrypoint make(String scriptName) { IClass cls = cha.lookupClass( TypeReference.findOrCreate(scriptType.getClassLoader().getReference(), scriptName)); assert cls != null && cha.isSubclassOf(cls, scriptType) && !cls.isAbstract() : String.valueOf(cls) + " for " + scriptName; for (IMethod method : cls.getDeclaredMethods()) { if (keep()) { return new ScriptEntryPoint(method); } } assert false; return null; } }
3,578
28.825
96
java
WALA
WALA-master/cast/src/main/java/com/ibm/wala/cast/ipa/callgraph/StandardFunctionTargetSelector.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.cast.ipa.callgraph; import com.ibm.wala.cast.types.AstMethodReference; import com.ibm.wala.cast.types.AstTypeReference; import com.ibm.wala.classLoader.CallSiteReference; import com.ibm.wala.classLoader.IClass; import com.ibm.wala.classLoader.IMethod; import com.ibm.wala.ipa.callgraph.CGNode; import com.ibm.wala.ipa.callgraph.MethodTargetSelector; import com.ibm.wala.ipa.cha.IClassHierarchy; import com.ibm.wala.types.ClassLoaderReference; import com.ibm.wala.types.TypeReference; public class StandardFunctionTargetSelector implements MethodTargetSelector { private final IClassHierarchy cha; private final MethodTargetSelector base; public StandardFunctionTargetSelector(IClassHierarchy cha, MethodTargetSelector base) { assert cha != null; this.cha = cha; this.base = base; } @Override public IMethod getCalleeTarget(CGNode caller, CallSiteReference site, IClass receiver) { ClassLoaderReference loader = (site.isStatic() || receiver == null) ? site.getDeclaredTarget().getDeclaringClass().getClassLoader() : receiver.getClassLoader().getReference(); TypeReference functionTypeRef = TypeReference.findOrCreate(loader, AstTypeReference.functionTypeName); IClass declarer = site.isStatic() ? cha.lookupClass(site.getDeclaredTarget().getDeclaringClass()) : receiver; if (declarer == null) { System.err.println(("cannot find declarer for " + site + ", " + receiver + " in " + caller)); } IClass fun = cha.lookupClass(functionTypeRef); if (fun == null) { System.err.println( ("cannot find function " + functionTypeRef + " for " + site + ", " + receiver + " in " + caller)); } if (fun != null && declarer != null && cha.isSubclassOf(declarer, fun)) { return declarer.getMethod(AstMethodReference.fnSelector); } else { return base.getCalleeTarget(caller, site, receiver); } } public boolean mightReturnSyntheticMethod() { return true; } }
2,504
31.532468
99
java
WALA
WALA-master/cast/src/main/java/com/ibm/wala/cast/ipa/cha/CrossLanguageClassHierarchy.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.cast.ipa.cha; import com.ibm.wala.classLoader.ClassLoaderFactory; import com.ibm.wala.classLoader.IClass; import com.ibm.wala.classLoader.IClassLoader; import com.ibm.wala.classLoader.IField; import com.ibm.wala.classLoader.IMethod; import com.ibm.wala.classLoader.Language; import com.ibm.wala.core.util.strings.Atom; import com.ibm.wala.ipa.callgraph.AnalysisScope; import com.ibm.wala.ipa.cha.ClassHierarchyException; import com.ibm.wala.ipa.cha.ClassHierarchyFactory; import com.ibm.wala.ipa.cha.IClassHierarchy; import com.ibm.wala.types.ClassLoaderReference; import com.ibm.wala.types.FieldReference; import com.ibm.wala.types.MethodReference; import com.ibm.wala.types.Selector; import com.ibm.wala.types.TypeReference; import com.ibm.wala.util.collections.ComposedIterator; import com.ibm.wala.util.collections.HashMapFactory; import com.ibm.wala.util.collections.HashSetFactory; import com.ibm.wala.util.debug.Assertions; import java.util.Collection; import java.util.Iterator; import java.util.Map; import java.util.Set; /** * This class hierarchy represents a family of disjoint class hierarchies, one for each of a * selection of languages. The implementation creates a separate ClassHierarchy object for each * language, and this overall IClassHierarchy implementation delegates to the appropriate language * class hierarchy based on the language associated with the class loader of the given TypeReference * or IClass object. * * <p>Note that, because of this delegating structure and representation of multiple languages, the * getRootClass API call does not make sense for this hierarchy. In general, any code that wants to * use multiple language must deal with the fact that there is no longer a single root type. Each * individual language is still expected to have a root type, however. * * @author Julian Dolby (dolby@us.ibm.com) */ public class CrossLanguageClassHierarchy implements IClassHierarchy { private final ClassLoaderFactory loaderFactory; private final AnalysisScope analysisScope; private final Map<Atom, IClassHierarchy> hierarchies; @Override public ClassLoaderFactory getFactory() { return loaderFactory; } @Override public AnalysisScope getScope() { return analysisScope; } private IClassHierarchy getHierarchy(Atom language) { return hierarchies.get(language); } private IClassHierarchy getHierarchy(IClassLoader loader) { return getHierarchy(loader.getLanguage().getName()); } private IClassHierarchy getHierarchy(ClassLoaderReference loader) { return getHierarchy(loader.getLanguage()); } private IClassHierarchy getHierarchy(IClass cls) { return getHierarchy(cls.getClassLoader()); } private IClassHierarchy getHierarchy(TypeReference cls) { return getHierarchy(cls.getClassLoader()); } private IClassHierarchy getHierarchy(MethodReference ref) { return getHierarchy(ref.getDeclaringClass()); } private IClassHierarchy getHierarchy(FieldReference ref) { return getHierarchy(ref.getDeclaringClass()); } @Override public IClassLoader[] getLoaders() { Set<IClassLoader> loaders = HashSetFactory.make(); for (ClassLoaderReference loaderReference : analysisScope.getLoaders()) { loaders.add(getLoader(loaderReference)); } return loaders.toArray(new IClassLoader[0]); } @Override public IClassLoader getLoader(ClassLoaderReference loaderRef) { return getHierarchy(loaderRef).getLoader(loaderRef); } @Override public boolean addClass(IClass klass) { return getHierarchy(klass).addClass(klass); } @Override public int getNumberOfClasses() { int total = 0; for (ClassLoaderReference loaderReference : analysisScope.getLoaders()) { total += getLoader(loaderReference).getNumberOfClasses(); } return total; } @Override public boolean isRootClass(IClass c) { return getHierarchy(c).isRootClass(c); } @Override public IClass getRootClass() { Assertions.UNREACHABLE(); return null; } @Override public int getNumber(IClass c) { return getHierarchy(c).getNumber(c); } @Override public Set<IMethod> getPossibleTargets(MethodReference ref) { return getHierarchy(ref).getPossibleTargets(ref); } @Override public Set<IMethod> getPossibleTargets(IClass receiverClass, MethodReference ref) { return getHierarchy(ref).getPossibleTargets(receiverClass, ref); } @Override public IMethod resolveMethod(MethodReference m) { return getHierarchy(m).resolveMethod(m); } @Override public IField resolveField(FieldReference f) { return getHierarchy(f).resolveField(f); } @Override public IField resolveField(IClass klass, FieldReference f) { return getHierarchy(klass).resolveField(klass, f); } @Override public IMethod resolveMethod(IClass receiver, Selector selector) { return getHierarchy(receiver).resolveMethod(receiver, selector); } @Override public IClass lookupClass(TypeReference A) { return getHierarchy(A).lookupClass(A); } // public boolean isSyntheticClass(IClass c) { // return getHierarchy(c).isSyntheticClass(c); // } @Override public boolean isInterface(TypeReference type) { return getHierarchy(type).isInterface(type); } @Override public IClass getLeastCommonSuperclass(IClass A, IClass B) { return getHierarchy(A).getLeastCommonSuperclass(A, B); } @Override public TypeReference getLeastCommonSuperclass(TypeReference A, TypeReference B) { return getHierarchy(A).getLeastCommonSuperclass(A, B); } @Override public boolean isSubclassOf(IClass c, IClass T) { return getHierarchy(c).isSubclassOf(c, T); } @Override public boolean implementsInterface(IClass c, IClass i) { return getHierarchy(c).implementsInterface(c, i); } @Override public Collection<IClass> computeSubClasses(TypeReference type) { return getHierarchy(type).computeSubClasses(type); } @Override public Collection<TypeReference> getJavaLangRuntimeExceptionTypes() { return getHierarchy(TypeReference.JavaLangRuntimeException).getJavaLangErrorTypes(); } @Override public Collection<TypeReference> getJavaLangErrorTypes() { return getHierarchy(TypeReference.JavaLangError).getJavaLangErrorTypes(); } @Override public Set<IClass> getImplementors(TypeReference type) { return getHierarchy(type).getImplementors(type); } @Override public int getNumberOfImmediateSubclasses(IClass klass) { return getHierarchy(klass).getNumberOfImmediateSubclasses(klass); } @Override public Collection<IClass> getImmediateSubclasses(IClass klass) { return getHierarchy(klass).getImmediateSubclasses(klass); } @Override public boolean isAssignableFrom(IClass c1, IClass c2) { return getHierarchy(c1).isAssignableFrom(c1, c2); } @Override public Iterator<IClass> iterator() { return new ComposedIterator<>(analysisScope.getLoaders().iterator()) { @Override public Iterator<IClass> makeInner(ClassLoaderReference o) { IClassLoader ldr = getLoader(o); return ldr.iterateAllClasses(); } }; } private CrossLanguageClassHierarchy( AnalysisScope scope, ClassLoaderFactory factory, Map<Atom, IClassHierarchy> hierarchies) { this.analysisScope = scope; this.loaderFactory = factory; this.hierarchies = hierarchies; } public static CrossLanguageClassHierarchy make(AnalysisScope scope, ClassLoaderFactory factory) throws ClassHierarchyException { Set<Language> languages = scope.getBaseLanguages(); Map<Atom, IClassHierarchy> hierarchies = HashMapFactory.make(); for (Language L : languages) { Set<Language> ll = HashSetFactory.make(L.getDerivedLanguages()); ll.add(L); hierarchies.put(L.getName(), ClassHierarchyFactory.make(scope, factory, ll)); } return new CrossLanguageClassHierarchy(scope, factory, hierarchies); } /* BEGIN Custom change: unresolved classes */ @Override public Set<TypeReference> getUnresolvedClasses() { return HashSetFactory.make(); } /* END Custom change: unresolved classes */ }
8,549
29.427046
100
java
WALA
WALA-master/cast/src/main/java/com/ibm/wala/cast/ipa/lexical/LexicalModRef.java
/* * Copyright (c) 2008 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.cast.ipa.lexical; import com.ibm.wala.cast.ipa.callgraph.ScopeMappingInstanceKeys.ScopeMappingInstanceKey; import com.ibm.wala.cast.ir.ssa.AstLexicalAccess.Access; import com.ibm.wala.cast.ir.ssa.AstLexicalRead; import com.ibm.wala.cast.ir.ssa.AstLexicalWrite; import com.ibm.wala.ipa.callgraph.CGNode; import com.ibm.wala.ipa.callgraph.CallGraph; import com.ibm.wala.ipa.callgraph.CallGraphTransitiveClosure; import com.ibm.wala.ipa.callgraph.propagation.InstanceKey; import com.ibm.wala.ipa.callgraph.propagation.PointerAnalysis; import com.ibm.wala.ssa.IR; import com.ibm.wala.ssa.SSAInstruction; import com.ibm.wala.util.collections.HashSetFactory; import com.ibm.wala.util.collections.Iterator2Iterable; import com.ibm.wala.util.collections.Pair; import com.ibm.wala.util.intset.OrdinalSet; import java.util.Collection; import java.util.Map; /** Compute mod-ref information limited to accesses of lexical variables. */ public class LexicalModRef { public static LexicalModRef make(CallGraph cg, PointerAnalysis<InstanceKey> pa) { return new LexicalModRef(cg, pa); } private final CallGraph cg; private final PointerAnalysis<InstanceKey> pa; protected LexicalModRef(CallGraph cg, PointerAnalysis<InstanceKey> pa) { this.cg = cg; this.pa = pa; } /** * Compute the lexical variables possibly read by each {@link CGNode} and its transitive callees. * A lexical variable is represented as a pair (C,N), where C is the defining {@link CGNode} and N * is the {@link String} name. */ public Map<CGNode, OrdinalSet<Pair<CGNode, String>>> computeLexicalRef() { Map<CGNode, Collection<Pair<CGNode, String>>> scan = CallGraphTransitiveClosure.collectNodeResults(cg, this::scanNodeForLexReads); return CallGraphTransitiveClosure.transitiveClosure(cg, scan); } /** * Compute the lexical variables possibly modified by each {@link CGNode} and its transitive * callees. A lexical variable is represented as a pair (C,N), where C is the defining {@link * CGNode} and N is the {@link String} name. */ public Map<CGNode, OrdinalSet<Pair<CGNode, String>>> computeLexicalMod() { Map<CGNode, Collection<Pair<CGNode, String>>> scan = CallGraphTransitiveClosure.collectNodeResults(cg, this::scanNodeForLexWrites); return CallGraphTransitiveClosure.transitiveClosure(cg, scan); } protected Collection<Pair<CGNode, String>> scanNodeForLexReads(CGNode n) { Collection<Pair<CGNode, String>> result = HashSetFactory.make(); IR ir = n.getIR(); if (ir != null) { for (SSAInstruction instr : Iterator2Iterable.make(ir.iterateNormalInstructions())) { if (instr instanceof AstLexicalRead) { AstLexicalRead read = (AstLexicalRead) instr; for (Access a : read.getAccesses()) { Pair<String, String> nameAndDefiner = a.getName(); result.addAll(getNodeNamePairsForAccess(n, nameAndDefiner)); } } } } return result; } protected Collection<Pair<CGNode, String>> scanNodeForLexWrites(CGNode n) { Collection<Pair<CGNode, String>> result = HashSetFactory.make(); IR ir = n.getIR(); if (ir != null) { for (SSAInstruction instr : Iterator2Iterable.make(ir.iterateNormalInstructions())) { if (instr instanceof AstLexicalWrite) { AstLexicalWrite write = (AstLexicalWrite) instr; for (Access a : write.getAccesses()) { Pair<String, String> nameAndDefiner = a.getName(); result.addAll(getNodeNamePairsForAccess(n, nameAndDefiner)); } } } } return result; } private Collection<Pair<CGNode, String>> getNodeNamePairsForAccess( CGNode n, Pair<String, String> nameAndDefiner) { Collection<Pair<CGNode, String>> result = HashSetFactory.make(); // use scope-mapping instance keys in pointer analysis. may need a different // scheme for CG construction not based on pointer analysis OrdinalSet<InstanceKey> functionValues = pa.getPointsToSet(pa.getHeapModel().getPointerKeyForLocal(n, 1)); for (InstanceKey ik : functionValues) { if (ik instanceof ScopeMappingInstanceKey) { ScopeMappingInstanceKey smik = (ScopeMappingInstanceKey) ik; for (CGNode definerNode : Iterator2Iterable.make(smik.getFunargNodes(nameAndDefiner))) { result.add(Pair.make(definerNode, nameAndDefiner.fst)); } } } return result; } }
4,850
39.090909
100
java
WALA
WALA-master/cast/src/main/java/com/ibm/wala/cast/ipa/modref/AstModRef.java
/* * Copyright (c) 2013 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.cast.ipa.modref; import com.ibm.wala.cast.ipa.callgraph.AstHeapModel; import com.ibm.wala.cast.ir.ssa.AstAssertInstruction; import com.ibm.wala.cast.ir.ssa.AstEchoInstruction; import com.ibm.wala.cast.ir.ssa.AstGlobalRead; import com.ibm.wala.cast.ir.ssa.AstGlobalWrite; import com.ibm.wala.cast.ir.ssa.AstInstructionVisitor; import com.ibm.wala.cast.ir.ssa.AstIsDefinedInstruction; import com.ibm.wala.cast.ir.ssa.AstLexicalRead; import com.ibm.wala.cast.ir.ssa.AstLexicalWrite; import com.ibm.wala.cast.ir.ssa.AstPropertyRead; import com.ibm.wala.cast.ir.ssa.AstPropertyWrite; import com.ibm.wala.cast.ir.ssa.EachElementGetInstruction; import com.ibm.wala.cast.ir.ssa.EachElementHasNextInstruction; import com.ibm.wala.ipa.callgraph.CGNode; import com.ibm.wala.ipa.callgraph.propagation.InstanceKey; import com.ibm.wala.ipa.callgraph.propagation.PointerAnalysis; import com.ibm.wala.ipa.callgraph.propagation.PointerKey; import com.ibm.wala.ipa.modref.ExtendedHeapModel; import com.ibm.wala.ipa.modref.ModRef; import com.ibm.wala.util.collections.Iterator2Iterable; import java.util.Collection; public class AstModRef<T extends InstanceKey> extends ModRef<T> { @Override public ExtendedHeapModel makeHeapModel(PointerAnalysis<T> pa) { return (AstHeapModel) pa.getHeapModel(); } protected static class AstRefVisitor<T extends InstanceKey> extends RefVisitor<T, AstHeapModel> implements AstInstructionVisitor { protected AstRefVisitor( CGNode n, Collection<PointerKey> result, PointerAnalysis<T> pa, AstHeapModel h) { super(n, result, pa, h); } @Override public void visitPropertyRead(AstPropertyRead instruction) { PointerKey obj = h.getPointerKeyForLocal(n, instruction.getObjectRef()); PointerKey prop = h.getPointerKeyForLocal(n, instruction.getMemberRef()); for (InstanceKey o : pa.getPointsToSet(obj)) { for (InstanceKey p : pa.getPointsToSet(prop)) { for (PointerKey x : Iterator2Iterable.make(h.getPointerKeysForReflectedFieldRead(o, p))) { assert x != null : instruction; result.add(x); } } } } @Override public void visitPropertyWrite(AstPropertyWrite instruction) { // do nothing } @Override public void visitAstLexicalRead(AstLexicalRead instruction) {} @Override public void visitAstLexicalWrite(AstLexicalWrite instruction) {} @Override public void visitAstGlobalRead(AstGlobalRead instruction) {} @Override public void visitAstGlobalWrite(AstGlobalWrite instruction) {} @Override public void visitAssert(AstAssertInstruction instruction) {} @Override public void visitEachElementGet(EachElementGetInstruction inst) {} @Override public void visitEachElementHasNext(EachElementHasNextInstruction inst) {} @Override public void visitIsDefined(AstIsDefinedInstruction inst) {} @Override public void visitEcho(AstEchoInstruction inst) {} } @Override protected RefVisitor<T, ? extends ExtendedHeapModel> makeRefVisitor( CGNode n, Collection<PointerKey> result, PointerAnalysis<T> pa, ExtendedHeapModel h) { return new AstRefVisitor<>(n, result, pa, (AstHeapModel) h); } protected static class AstModVisitor<T extends InstanceKey> extends ModVisitor<T, AstHeapModel> implements AstInstructionVisitor { protected AstModVisitor( CGNode n, Collection<PointerKey> result, AstHeapModel h, PointerAnalysis<T> pa) { super(n, result, h, pa, true); } @Override public void visitAstLexicalRead(AstLexicalRead instruction) {} @Override public void visitAstLexicalWrite(AstLexicalWrite instruction) {} @Override public void visitAstGlobalRead(AstGlobalRead instruction) {} @Override public void visitAstGlobalWrite(AstGlobalWrite instruction) {} @Override public void visitAssert(AstAssertInstruction instruction) {} @Override public void visitEachElementGet(EachElementGetInstruction inst) {} @Override public void visitEachElementHasNext(EachElementHasNextInstruction inst) {} @Override public void visitIsDefined(AstIsDefinedInstruction inst) {} @Override public void visitEcho(AstEchoInstruction inst) {} @Override public void visitPropertyRead(AstPropertyRead instruction) { // do nothing } @Override public void visitPropertyWrite(AstPropertyWrite instruction) { PointerKey obj = h.getPointerKeyForLocal(n, instruction.getObjectRef()); PointerKey prop = h.getPointerKeyForLocal(n, instruction.getMemberRef()); for (T o : pa.getPointsToSet(obj)) { for (T p : pa.getPointsToSet(prop)) { for (PointerKey x : Iterator2Iterable.make(h.getPointerKeysForReflectedFieldWrite(o, p))) { assert x != null : instruction; result.add(x); } } } } } @Override protected ModVisitor<T, ? extends ExtendedHeapModel> makeModVisitor( CGNode n, Collection<PointerKey> result, PointerAnalysis<T> pa, ExtendedHeapModel h, boolean ignoreAllocHeapDefs) { return new AstModVisitor<>(n, result, (AstHeapModel) h, pa); } }
5,632
32.331361
100
java
WALA
WALA-master/cast/src/main/java/com/ibm/wala/cast/ir/cfg/AstInducedCFG.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.cast.ir.cfg; import com.ibm.wala.cast.ir.ssa.AstAssertInstruction; import com.ibm.wala.cast.ir.ssa.AstEchoInstruction; import com.ibm.wala.cast.ir.ssa.AstGlobalRead; import com.ibm.wala.cast.ir.ssa.AstGlobalWrite; import com.ibm.wala.cast.ir.ssa.AstInstructionVisitor; import com.ibm.wala.cast.ir.ssa.AstIsDefinedInstruction; import com.ibm.wala.cast.ir.ssa.AstLexicalRead; import com.ibm.wala.cast.ir.ssa.AstLexicalWrite; import com.ibm.wala.cast.ir.ssa.AstPropertyRead; import com.ibm.wala.cast.ir.ssa.AstPropertyWrite; import com.ibm.wala.cast.ir.ssa.EachElementGetInstruction; import com.ibm.wala.cast.ir.ssa.EachElementHasNextInstruction; import com.ibm.wala.cfg.InducedCFG; import com.ibm.wala.classLoader.IMethod; import com.ibm.wala.ipa.callgraph.Context; import com.ibm.wala.ssa.SSAInstruction; public class AstInducedCFG extends InducedCFG { public AstInducedCFG(SSAInstruction[] instructions, IMethod method, Context context) { super(instructions, method, context); } protected class AstPEIVisitor extends PEIVisitor implements AstInstructionVisitor { protected AstPEIVisitor(boolean[] r) { super(r); } @Override public void visitPropertyRead(AstPropertyRead inst) {} @Override public void visitPropertyWrite(AstPropertyWrite inst) {} @Override public void visitAstLexicalRead(AstLexicalRead inst) {} @Override public void visitAstLexicalWrite(AstLexicalWrite inst) {} @Override public void visitAstGlobalRead(AstGlobalRead instruction) {} @Override public void visitAstGlobalWrite(AstGlobalWrite instruction) {} @Override public void visitAssert(AstAssertInstruction instruction) {} @Override public void visitEachElementHasNext(EachElementHasNextInstruction inst) {} @Override public void visitEachElementGet(EachElementGetInstruction inst) {} @Override public void visitIsDefined(AstIsDefinedInstruction inst) {} @Override public void visitEcho(AstEchoInstruction inst) {} } protected class AstBranchVisitor extends BranchVisitor implements AstInstructionVisitor { protected AstBranchVisitor(boolean[] r) { super(r); } @Override public void visitPropertyRead(AstPropertyRead inst) {} @Override public void visitPropertyWrite(AstPropertyWrite inst) {} @Override public void visitAstLexicalRead(AstLexicalRead inst) {} @Override public void visitAstLexicalWrite(AstLexicalWrite inst) {} @Override public void visitAstGlobalRead(AstGlobalRead instruction) {} @Override public void visitAstGlobalWrite(AstGlobalWrite instruction) {} @Override public void visitAssert(AstAssertInstruction instruction) {} @Override public void visitEachElementHasNext(EachElementHasNextInstruction inst) {} @Override public void visitEachElementGet(EachElementGetInstruction inst) {} @Override public void visitIsDefined(AstIsDefinedInstruction inst) {} @Override public void visitEcho(AstEchoInstruction inst) {} } @Override protected BranchVisitor makeBranchVisitor(boolean[] r) { return new AstBranchVisitor(r); } @Override protected PEIVisitor makePEIVisitor(boolean[] r) { return new AstPEIVisitor(r); } }
3,670
28.134921
91
java
WALA
WALA-master/cast/src/main/java/com/ibm/wala/cast/ir/cfg/DelegatingCFG.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.cast.ir.cfg; import com.ibm.wala.cfg.ControlFlowGraph; import com.ibm.wala.cfg.IBasicBlock; import com.ibm.wala.classLoader.IMethod; import com.ibm.wala.util.graph.AbstractNumberedGraph; import com.ibm.wala.util.graph.NumberedEdgeManager; import com.ibm.wala.util.graph.NumberedNodeManager; import com.ibm.wala.util.intset.BitVector; import java.util.Collection; import java.util.List; public class DelegatingCFG<I, T extends IBasicBlock<I>> extends AbstractNumberedGraph<T> implements ControlFlowGraph<I, T> { protected final ControlFlowGraph<I, T> parent; public DelegatingCFG(ControlFlowGraph<I, T> parent) { this.parent = parent; } @Override protected NumberedNodeManager<T> getNodeManager() { return parent; } @Override protected NumberedEdgeManager<T> getEdgeManager() { return parent; } @Override public T entry() { return parent.entry(); } @Override public T exit() { return parent.exit(); } @Override public BitVector getCatchBlocks() { return parent.getCatchBlocks(); } @Override public T getBlockForInstruction(int index) { return parent.getBlockForInstruction(index); } @Override public I[] getInstructions() { return parent.getInstructions(); } @Override public int getProgramCounter(int index) { return parent.getProgramCounter(index); } @Override public IMethod getMethod() { return parent.getMethod(); } @Override public List<T> getExceptionalSuccessors(T b) { return parent.getExceptionalSuccessors(b); } @Override public Collection<T> getNormalSuccessors(T b) { return parent.getNormalSuccessors(b); } @Override public Collection<T> getExceptionalPredecessors(T b) { return parent.getExceptionalPredecessors(b); } @Override public Collection<T> getNormalPredecessors(T b) { return parent.getNormalPredecessors(b); } }
2,293
22.649485
88
java
WALA
WALA-master/cast/src/main/java/com/ibm/wala/cast/ir/cfg/Util.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.cast.ir.cfg; import com.ibm.wala.cfg.ControlFlowGraph; import com.ibm.wala.cfg.IBasicBlock; import com.ibm.wala.util.collections.Iterator2Iterable; import com.ibm.wala.util.debug.Assertions; public class Util { public static <I, T extends IBasicBlock<I>> int whichPred(ControlFlowGraph<I, T> CFG, T Y, T X) { int i = 0; for (Object N : Iterator2Iterable.make(CFG.getPredNodes(Y))) { if (N == X) return i; ++i; } Assertions.UNREACHABLE(); return -1; } }
889
27.709677
99
java
WALA
WALA-master/cast/src/main/java/com/ibm/wala/cast/ir/ssa/AbstractReflectiveGet.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.cast.ir.ssa; import com.ibm.wala.ssa.ReflectiveMemberAccess; import com.ibm.wala.ssa.SymbolTable; /** * This abstract class represents field (a.k.a property) reads in which the field name is not a * constant, but rather a computed value. This is common in scripting languages, and so this base * class is shared across all languages that need such accesses. * * @author Julian Dolby (dolby@us.ibm.com) */ public abstract class AbstractReflectiveGet extends ReflectiveMemberAccess { private final int result; public AbstractReflectiveGet(int iindex, int result, int objectRef, int memberRef) { super(iindex, objectRef, memberRef); this.result = result; } @Override public String toString(SymbolTable symbolTable) { return getValueString(symbolTable, result) + " = " + super.toString(symbolTable); } /** @see com.ibm.wala.ssa.SSAInstruction#getDef() */ @Override public boolean hasDef() { return true; } @Override public int getDef() { return result; } @Override public int getDef(int i) { return result; } /** @see com.ibm.wala.ssa.SSAInstruction#getNumberOfUses() */ @Override public int getNumberOfUses() { return 2; } @Override public int getNumberOfDefs() { return 1; } }
1,664
25.428571
97
java
WALA
WALA-master/cast/src/main/java/com/ibm/wala/cast/ir/ssa/AbstractReflectivePut.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.cast.ir.ssa; import com.ibm.wala.ssa.ReflectiveMemberAccess; import com.ibm.wala.ssa.SymbolTable; /** * This abstract class represents field (a.k.a property) writes in which the field name is not a * constant, but rather a computed value. This is common in scripting languages, and so this base * class is shared across all languages that need such accesses. * * @author Julian Dolby (dolby@us.ibm.com) */ public abstract class AbstractReflectivePut extends ReflectiveMemberAccess { private final int value; public AbstractReflectivePut(int iindex, int objectRef, int memberRef, int value) { super(iindex, objectRef, memberRef); this.value = value; } @Override public String toString(SymbolTable symbolTable) { return super.toString(symbolTable) + " = " + getValueString(symbolTable, value); } /** @see com.ibm.wala.ssa.SSAInstruction#getDef() */ @Override public int getDef() { return -1; } /** @see com.ibm.wala.ssa.SSAInstruction#getNumberOfUses() */ @Override public int getNumberOfUses() { return 3; } public int getValue() { return getUse(2); } @Override public int getUse(int index) { if (index == 2) return value; else return super.getUse(index); } }
1,639
27.275862
97
java
WALA
WALA-master/cast/src/main/java/com/ibm/wala/cast/ir/ssa/AbstractSSAConversion.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.cast.ir.ssa; import com.ibm.wala.ssa.IR; import com.ibm.wala.ssa.ISSABasicBlock; import com.ibm.wala.ssa.SSACFG; import com.ibm.wala.ssa.SSACFG.BasicBlock; import com.ibm.wala.ssa.SSAInstruction; import com.ibm.wala.ssa.SSAOptions; import com.ibm.wala.ssa.SSAOptions.DefaultValues; import com.ibm.wala.ssa.SSAPhiInstruction; import com.ibm.wala.ssa.SymbolTable; import com.ibm.wala.util.collections.ArrayIterator; import com.ibm.wala.util.collections.IntStack; import com.ibm.wala.util.collections.Iterator2Iterable; import com.ibm.wala.util.graph.Graph; import com.ibm.wala.util.graph.dominators.DominanceFrontiers; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.Set; /** * Abstract core of traditional SSA conversion (Cytron et al.). * * <p>This implementation is abstract in the sense that it is designed to work over the instructions * and CFG of a Domo IR, but it is abstract with respect to several integral portions of the * traditional algorithm: * * <UL> * <LI>The notion of uses and defs of a given instruction. * <LI>Assignments (&lt;def&gt; := &lt;use&gt;) that are be copy-propagated away * <LI>Which values are constants---i.e. have no definition. * <LI>Any value numbers to be skipped during SSA construction * <LI>Special initialization and exit block processing. * </UL> * * @author Julian dolby (dolby@us.ibm.com) */ public abstract class AbstractSSAConversion { protected abstract int getNumberOfDefs(SSAInstruction inst); protected abstract int getDef(SSAInstruction inst, int index); protected abstract int getNumberOfUses(SSAInstruction inst); protected abstract int getUse(SSAInstruction inst, int index); protected abstract boolean isAssignInstruction(SSAInstruction inst); protected abstract int getMaxValueNumber(); protected abstract boolean isLive(SSACFG.BasicBlock Y, int V); protected abstract boolean skip(int vn); protected abstract boolean isConstant(int valueNumber); protected abstract int getNextNewValueNumber(); protected abstract void initializeVariables(); protected abstract void repairExit(); protected abstract void placeNewPhiAt(int value, SSACFG.BasicBlock Y); protected abstract SSAPhiInstruction getPhi(SSACFG.BasicBlock B, int index); protected abstract void setPhi(SSACFG.BasicBlock B, int index, SSAPhiInstruction inst); protected abstract SSAPhiInstruction repairPhiDefs(SSAPhiInstruction phi, int[] newDefs); protected abstract void repairPhiUse( SSACFG.BasicBlock BB, int phiIndex, int rvalIndex, int newRval); protected abstract void repairInstructionUses(SSAInstruction inst, int index, int[] newUses); protected abstract void repairInstructionDefs( SSAInstruction inst, int index, int[] newDefs, int[] newUses); protected abstract void pushAssignment(SSAInstruction inst, int index, int newRhs); protected abstract void popAssignment(SSAInstruction inst, int index); protected final SSACFG CFG; protected final DominanceFrontiers<ISSABasicBlock> DF; private final Graph<ISSABasicBlock> dominatorTree; protected final int[] phiCounts; protected final SSAInstruction[] instructions; private final int flags[]; protected final SymbolTable symbolTable; protected final DefaultValues defaultValues; protected IntStack S[]; protected int C[]; protected int valueMap[]; private Set<SSACFG.BasicBlock>[] assignmentMap; protected AbstractSSAConversion(IR ir, SSAOptions options) { this.CFG = ir.getControlFlowGraph(); this.DF = new DominanceFrontiers<>(ir.getControlFlowGraph(), ir.getControlFlowGraph().entry()); this.dominatorTree = DF.dominatorTree(); this.flags = new int[2 * ir.getControlFlowGraph().getNumberOfNodes()]; this.instructions = getInstructions(ir); this.phiCounts = new int[CFG.getNumberOfNodes()]; this.symbolTable = ir.getSymbolTable(); this.defaultValues = options.getDefaultValues(); } // // top-level control // protected void perform() { init(); placePhiNodes(); renameVariables(); } // // initialization // protected SSAInstruction[] getInstructions(IR ir) { return ir.getInstructions(); } protected final Iterator<SSAInstruction> iterateInstructions(IR ir) { return new ArrayIterator<>(getInstructions(ir)); } protected void init() { this.S = new IntStack[getMaxValueNumber() + 1]; this.C = new int[getMaxValueNumber() + 1]; this.valueMap = new int[getMaxValueNumber() + 1]; makeAssignmentMap(); } @SuppressWarnings("unchecked") private void makeAssignmentMap() { this.assignmentMap = new Set[getMaxValueNumber() + 1]; for (ISSABasicBlock issaBasicBlock : CFG) { SSACFG.BasicBlock BB = (SSACFG.BasicBlock) issaBasicBlock; if (BB.getFirstInstructionIndex() >= 0) { for (SSAInstruction inst : BB) { if (inst != null) { for (int j = 0; j < getNumberOfDefs(inst); j++) { addDefiningBlock(assignmentMap, BB, getDef(inst, j)); } } } } } } private void addDefiningBlock(Set<SSACFG.BasicBlock>[] A, SSACFG.BasicBlock BB, int i) { if (!skip(i)) { if (A[i] == null) { A[i] = new LinkedHashSet<>(2); } A[i].add(BB); } } // // place phi nodes phase of traditional algorithm // protected void placePhiNodes() { int IterCount = 0; for (ISSABasicBlock issaBasicBlock : CFG) { SSACFG.BasicBlock X = (SSACFG.BasicBlock) issaBasicBlock; setHasAlready(X, 0); setWork(X, 0); } Set<BasicBlock> W = new LinkedHashSet<>(); for (int V = 0; V < assignmentMap.length; V++) { // some things (e.g. constants) have no defs at all if (assignmentMap[V] == null) continue; // ignore values as requested if (skip(V)) continue; IterCount++; for (BasicBlock X : assignmentMap[V]) { setWork(X, IterCount); W.add(X); } while (!W.isEmpty()) { SSACFG.BasicBlock X = W.iterator().next(); W.remove(X); for (ISSABasicBlock IY : Iterator2Iterable.make(DF.getDominanceFrontier(X))) { SSACFG.BasicBlock Y = (SSACFG.BasicBlock) IY; if (getHasAlready(Y) < IterCount) { if (isLive(Y, V)) { placeNewPhiAt(V, Y); phiCounts[Y.getGraphNodeId()]++; } setHasAlready(Y, IterCount); if (getWork(Y) < IterCount) { setWork(Y, IterCount); W.add(Y); } } } } } } private int getWork(SSACFG.BasicBlock BB) { return flags[BB.getGraphNodeId() * 2 + 1]; } private void setWork(SSACFG.BasicBlock BB, int v) { flags[BB.getGraphNodeId() * 2 + 1] = v; } private int getHasAlready(SSACFG.BasicBlock BB) { return flags[BB.getGraphNodeId() * 2]; } private void setHasAlready(SSACFG.BasicBlock BB, int v) { flags[BB.getGraphNodeId() * 2] = v; } // // rename variables phase of traditional algorithm // private void renameVariables() { for (int V = 1; V <= getMaxValueNumber(); V++) { if (!skip(V)) { C[V] = 0; S[V] = new IntStack(); } } initializeVariables(); SEARCH(CFG.entry()); } /** * Stack frames for the SEARCH recursion. Used for converting the recursion to an iteration and * avoiding stack overflow. * * @author yinnonh */ private static class Frame { public final SSACFG.BasicBlock X; public final Iterator<ISSABasicBlock> i; // iterator o public Frame(SSACFG.BasicBlock X, Iterator<ISSABasicBlock> i) { this.X = X; this.i = i; } } private void SEARCH(SSACFG.BasicBlock X) { // original method was recursive: // SearchPreRec(X) // for (BasicBlock Y: childs(X)) // SEARCH(Y) // SearchPostRec(X) ArrayList<Frame> stack = new ArrayList<>(); SearchPreRec(X); push(stack, new Frame(X, dominatorTree.getSuccNodes(X))); // invariant: pre-rec phase was performed for elements in the queue. while (!stack.isEmpty()) { Frame f = peek(stack); if (f.i.hasNext()) { // iterate next child BasicBlock next = (BasicBlock) f.i.next(); SearchPreRec(next); push(stack, new Frame(next, dominatorTree.getSuccNodes(next))); } else { // finished iterating children, time to "return" SearchPostRec(f.X); pop(stack); } } } private static <T> void push(ArrayList<T> stack, T elt) { stack.add(elt); } private static <T> T peek(ArrayList<T> stack) { return stack.get(stack.size() - 1); } private static <T> T pop(ArrayList<T> stack) { T e = stack.get(stack.size() - 1); stack.remove(stack.size() - 1); return e; } private void SearchPreRec(SSACFG.BasicBlock X) { int id = X.getGraphNodeId(); int Xf = X.getFirstInstructionIndex(); // first loop for (int i = 0; i < phiCounts[id]; i++) { SSAPhiInstruction phi = getPhi(X, i); if (!skipRepair(phi, -1)) { setPhi(X, i, repairPhiDefs(phi, makeNewDefs(phi))); } } for (int i = Xf; i <= X.getLastInstructionIndex(); i++) { SSAInstruction inst = instructions[i]; if (isAssignInstruction(inst)) { int lhs = getDef(inst, 0); int rhs = getUse(inst, 0); int newRhs = skip(rhs) ? rhs : top(rhs); S[lhs].push(newRhs); pushAssignment(inst, i, newRhs); } else { if (!skipRepair(inst, i)) { int[] newUses = makeNewUses(inst); repairInstructionUses(inst, i, newUses); int[] newDefs = makeNewDefs(inst); repairInstructionDefs(inst, i, newDefs, newUses); } } } if (X.isExitBlock()) { repairExit(); } for (ISSABasicBlock IY : Iterator2Iterable.make(CFG.getSuccNodes(X))) { SSACFG.BasicBlock Y = (SSACFG.BasicBlock) IY; int Y_id = Y.getGraphNodeId(); int j = com.ibm.wala.cast.ir.cfg.Util.whichPred(CFG, Y, X); for (int i = 0; i < phiCounts[Y_id]; i++) { SSAPhiInstruction phi = getPhi(Y, i); int oldUse = getUse(phi, j); int newUse = skip(oldUse) ? oldUse : top(oldUse); repairPhiUse(Y, i, j, newUse); } } } private void SearchPostRec(SSACFG.BasicBlock X) { int id = X.getGraphNodeId(); int Xf = X.getFirstInstructionIndex(); for (int i = 0; i < phiCounts[id]; i++) { SSAInstruction A = getPhi(X, i); for (int j = 0; j < getNumberOfDefs(A); j++) { if (!skip(getDef(A, j))) { S[valueMap[getDef(A, j)]].pop(); } } } for (int i = Xf; i <= X.getLastInstructionIndex(); i++) { SSAInstruction A = instructions[i]; if (isAssignInstruction(A)) { S[getDef(A, 0)].pop(); popAssignment(A, i); } else if (A != null) { for (int j = 0; j < getNumberOfDefs(A); j++) { if (!skip(getDef(A, j))) { S[valueMap[getDef(A, j)]].pop(); } } } } } private int[] makeNewUses(SSAInstruction inst) { int[] newUses = new int[getNumberOfUses(inst)]; for (int j = 0; j < getNumberOfUses(inst); j++) { newUses[j] = skip(getUse(inst, j)) ? getUse(inst, j) : top(getUse(inst, j)); } return newUses; } private int[] makeNewDefs(SSAInstruction inst) { int[] newDefs = new int[getNumberOfDefs(inst)]; for (int j = 0; j < getNumberOfDefs(inst); j++) { if (skip(getDef(inst, j))) { newDefs[j] = getDef(inst, j); } else { int ii = getNextNewValueNumber(); if (valueMap.length <= ii) { valueMap = Arrays.copyOf(valueMap, valueMap.length * 2 + ii + 1); } valueMap[ii] = getDef(inst, j); S[getDef(inst, j)].push(ii); newDefs[j] = ii; } } return newDefs; } protected boolean skipRepair(SSAInstruction inst, @SuppressWarnings("unused") int index) { if (inst == null) return true; for (int i = 0; i < getNumberOfDefs(inst); i++) if (!skip(getDef(inst, i))) return false; for (int i = 0; i < getNumberOfUses(inst); i++) if (!skip(getUse(inst, i))) return false; return true; } protected void fail(int v) { assert isConstant(v) || !S[v].isEmpty() : "bad stack for " + v + " while SSA converting"; } protected boolean hasDefaultValue(int valueNumber) { return (defaultValues != null) && (defaultValues.getDefaultValue(symbolTable, valueNumber) != -1); } protected int getDefaultValue(int valueNumber) { return defaultValues.getDefaultValue(symbolTable, valueNumber); } protected int top(int v) { if (!(isConstant(v) || !S[v].isEmpty())) { if (hasDefaultValue(v)) { return getDefaultValue(v); } else { fail(v); } } assert !S[v].isEmpty(); return isConstant(v) ? v : S[v].peek(); } }
13,425
28.060606
100
java
WALA
WALA-master/cast/src/main/java/com/ibm/wala/cast/ir/ssa/AssignInstruction.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.cast.ir.ssa; import com.ibm.wala.ssa.SSAInstruction; import com.ibm.wala.ssa.SSAInstructionFactory; import com.ibm.wala.ssa.SSAUnaryOpInstruction; import com.ibm.wala.ssa.SymbolTable; /** * A simple assignment statement. Only appears in the IR before SSA conversion, and temporarily when * needed to undo copy propagation during processing of new lexical definitions and uses. * * @author Julian Dolby (dolby@us.ibm.com) */ public class AssignInstruction extends SSAUnaryOpInstruction { /** create the assignment v_result := v_val */ public AssignInstruction(int iindex, int result, int val) { super(iindex, null, result, val); assert result != val; assert result != -1; assert val != -1; } /** @see com.ibm.wala.ssa.SSAInstruction#copyForSSA(SSAInstructionFactory, int[], int[]) */ @Override public SSAInstruction copyForSSA(SSAInstructionFactory insts, int[] defs, int[] uses) { return ((AstInstructionFactory) insts) .AssignInstruction( iIndex(), defs == null ? getDef(0) : defs[0], uses == null ? getUse(0) : uses[0]); } /** @see com.ibm.wala.ssa.SSAInstruction#toString(SymbolTable) */ @Override public String toString(SymbolTable symbolTable) { return getValueString(symbolTable, result) + " := " + getValueString(symbolTable, val); } /** @see com.ibm.wala.ssa.SSAInstruction#visit(IVisitor) */ @Override public void visit(IVisitor v) { ((AstPreInstructionVisitor) v).visitAssign(this); } public int getVal() { return getUse(0); } }
1,933
32.344828
100
java
WALA
WALA-master/cast/src/main/java/com/ibm/wala/cast/ir/ssa/AstAbstractInstructionVisitor.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.cast.ir.ssa; import com.ibm.wala.ssa.SSAInstruction; public abstract class AstAbstractInstructionVisitor extends SSAInstruction.Visitor implements AstInstructionVisitor { @Override public void visitPropertyRead(AstPropertyRead instruction) {} @Override public void visitPropertyWrite(AstPropertyWrite instruction) {} @Override public void visitAstLexicalRead(AstLexicalRead instruction) {} @Override public void visitAstLexicalWrite(AstLexicalWrite instruction) {} @Override public void visitAstGlobalRead(AstGlobalRead instruction) {} @Override public void visitAstGlobalWrite(AstGlobalWrite instruction) {} @Override public void visitAssert(AstAssertInstruction instruction) {} @Override public void visitEachElementGet(EachElementGetInstruction inst) {} @Override public void visitEachElementHasNext(EachElementHasNextInstruction inst) {} @Override public void visitIsDefined(AstIsDefinedInstruction inst) {} @Override public void visitEcho(AstEchoInstruction inst) {} }
1,431
27.078431
82
java
WALA
WALA-master/cast/src/main/java/com/ibm/wala/cast/ir/ssa/AstAssertInstruction.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.cast.ir.ssa; import com.ibm.wala.ssa.SSAInstruction; import com.ibm.wala.ssa.SSAInstructionFactory; import com.ibm.wala.ssa.SymbolTable; import com.ibm.wala.types.TypeReference; import java.util.Collection; /** * An assert statement, as found in a variety of languages. It has a use which is the value being * asserted to be true. Additionally, there is flag which denotes whether the assertion is from a * specification (the usual case) or is an assertion introduced by "compilation" of whatever sort * (e.g. to add assertions regarding loop conditions needed by bounded model checking). * * @author Julian Dolby (dolby@us.ibm.com) */ public class AstAssertInstruction extends SSAInstruction { private final int value; private final boolean fromSpecification; public AstAssertInstruction(int iindex, int value, boolean fromSpecification) { super(iindex); this.value = value; this.fromSpecification = fromSpecification; } @Override public int getNumberOfUses() { return 1; } @Override public int getUse(int i) { assert i == 0; return value; } @Override public SSAInstruction copyForSSA(SSAInstructionFactory insts, int[] defs, int[] uses) { return ((AstInstructionFactory) insts) .AssertInstruction(iIndex(), uses == null ? value : uses[0], fromSpecification); } @Override public String toString(SymbolTable symbolTable) { return "assert " + getValueString(symbolTable, value) + " (fromSpec: " + fromSpecification + ')'; } @Override public void visit(IVisitor v) { ((AstInstructionVisitor) v).visitAssert(this); } @Override public int hashCode() { return 2177 * value; } @Override public Collection<TypeReference> getExceptionTypes() { return null; } @Override public boolean isFallThrough() { return true; } public boolean isFromSpecification() { return fromSpecification; } }
2,346
25.670455
97
java
WALA
WALA-master/cast/src/main/java/com/ibm/wala/cast/ir/ssa/AstConsumeInstruction.java
/* * Copyright (c) 2013 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.cast.ir.ssa; import com.ibm.wala.ssa.SSAInstruction; import com.ibm.wala.types.TypeReference; import com.ibm.wala.util.debug.Assertions; import java.util.Collection; import java.util.Collections; public abstract class AstConsumeInstruction extends SSAInstruction { protected final int[] rvals; public AstConsumeInstruction(int iindex, int[] rvals) { super(iindex); this.rvals = rvals; } @Override public int getNumberOfDefs() { return 0; } @Override public int getDef(int i) { Assertions.UNREACHABLE(); return -1; } @Override public int getNumberOfUses() { return rvals.length; } @Override public int getUse(int i) { return rvals[i]; } @Override public int hashCode() { int v = 1; for (int rval : rvals) { v *= rval; } return v; } @Override public boolean isFallThrough() { return true; } @Override public Collection<TypeReference> getExceptionTypes() { return Collections.emptySet(); } }
1,395
19.529412
72
java
WALA
WALA-master/cast/src/main/java/com/ibm/wala/cast/ir/ssa/AstEchoInstruction.java
/* * Copyright (c) 2013 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.cast.ir.ssa; import com.ibm.wala.ssa.SSAInstruction; import com.ibm.wala.ssa.SSAInstructionFactory; import com.ibm.wala.ssa.SymbolTable; public class AstEchoInstruction extends AstConsumeInstruction { public AstEchoInstruction(int iindex, int[] rvals) { super(iindex, rvals); } @Override public SSAInstruction copyForSSA(SSAInstructionFactory insts, int[] defs, int[] uses) { return ((AstInstructionFactory) insts).EchoInstruction(iIndex(), uses == null ? rvals : uses); } @Override public String toString(SymbolTable symbolTable) { StringBuilder result = new StringBuilder("echo/print "); for (int rval : rvals) { result.append(getValueString(symbolTable, rval)).append(' '); } return result.toString(); } @Override public void visit(IVisitor v) { ((AstInstructionVisitor) v).visitEcho(this); } }
1,250
28.093023
98
java
WALA
WALA-master/cast/src/main/java/com/ibm/wala/cast/ir/ssa/AstGlobalRead.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.cast.ir.ssa; import com.ibm.wala.ssa.SSAGetInstruction; import com.ibm.wala.ssa.SSAInstruction; import com.ibm.wala.ssa.SSAInstructionFactory; import com.ibm.wala.ssa.SymbolTable; import com.ibm.wala.types.FieldReference; import com.ibm.wala.types.TypeReference; import java.util.Collection; /** * A read of a global variable denoted by a FieldReference * * @author Julian Dolby (dolby@us.ibm.com) */ public class AstGlobalRead extends SSAGetInstruction { public AstGlobalRead(int iindex, int lhs, FieldReference global) { super(iindex, lhs, global); } @Override public SSAInstruction copyForSSA(SSAInstructionFactory insts, int[] defs, int[] uses) { return ((AstInstructionFactory) insts) .GlobalRead(iIndex(), (defs == null) ? getDef() : defs[0], getDeclaredField()); } @Override public String toString(SymbolTable symbolTable) { return getValueString(symbolTable, getDef()) + " = global:" + getGlobalName(); } @Override public void visit(IVisitor v) { if (v instanceof AstInstructionVisitor) ((AstInstructionVisitor) v).visitAstGlobalRead(this); } @Override public boolean isFallThrough() { return true; } @Override public Collection<TypeReference> getExceptionTypes() { return null; } public String getGlobalName() { return getDeclaredField().getName().toString(); } }
1,756
27.33871
97
java
WALA
WALA-master/cast/src/main/java/com/ibm/wala/cast/ir/ssa/AstGlobalWrite.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.cast.ir.ssa; import com.ibm.wala.ssa.SSAInstruction; import com.ibm.wala.ssa.SSAInstructionFactory; import com.ibm.wala.ssa.SSAPutInstruction; import com.ibm.wala.ssa.SymbolTable; import com.ibm.wala.types.FieldReference; import com.ibm.wala.types.TypeReference; import java.util.Collection; /** * A write of a global variable denoted by a FieldReference * * @author Julian Dolby (dolby@us.ibm.com) */ public class AstGlobalWrite extends SSAPutInstruction { public AstGlobalWrite(int iindex, FieldReference global, int rhs) { super(iindex, rhs, global); } @Override public SSAInstruction copyForSSA(SSAInstructionFactory insts, int[] defs, int[] uses) { return ((AstInstructionFactory) insts) .GlobalWrite(iIndex(), getDeclaredField(), (uses == null) ? getVal() : uses[0]); } @Override public String toString(SymbolTable symbolTable) { return "global:" + getGlobalName() + " = " + getValueString(symbolTable, getVal()); } @Override public void visit(IVisitor v) { if (v instanceof AstInstructionVisitor) ((AstInstructionVisitor) v).visitAstGlobalWrite(this); } @Override public boolean isFallThrough() { return true; } @Override public Collection<TypeReference> getExceptionTypes() { return null; } public String getGlobalName() { return getDeclaredField().getName().toString(); } }
1,766
27.5
98
java
WALA
WALA-master/cast/src/main/java/com/ibm/wala/cast/ir/ssa/AstIRFactory.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.cast.ir.ssa; import com.ibm.wala.cast.ir.ssa.SSAConversion.SSAInformation; import com.ibm.wala.cast.loader.AstMethod; import com.ibm.wala.cast.loader.AstMethod.LexicalInformation; import com.ibm.wala.cast.tree.CAstSourcePositionMap.Position; import com.ibm.wala.cfg.AbstractCFG; import com.ibm.wala.cfg.ControlFlowGraph; import com.ibm.wala.cfg.IBasicBlock; import com.ibm.wala.classLoader.IMethod; import com.ibm.wala.ipa.callgraph.Context; import com.ibm.wala.ssa.DefaultIRFactory; import com.ibm.wala.ssa.IR; import com.ibm.wala.ssa.IRFactory; import com.ibm.wala.ssa.SSACFG; import com.ibm.wala.ssa.SSACFG.ExceptionHandlerBasicBlock; import com.ibm.wala.ssa.SSAGetCaughtExceptionInstruction; import com.ibm.wala.ssa.SSAIndirectionData; import com.ibm.wala.ssa.SSAIndirectionData.Name; import com.ibm.wala.ssa.SSAInstruction; import com.ibm.wala.ssa.SSAOptions; import com.ibm.wala.ssa.SymbolTable; import com.ibm.wala.types.TypeReference; import java.util.Map; import java.util.Map.Entry; public class AstIRFactory<T extends IMethod> implements IRFactory<T> { public ControlFlowGraph<?, ?> makeCFG(final IMethod method) { return ((AstMethod) method).getControlFlowGraph(); } public static class AstDefaultIRFactory<T extends IMethod> extends DefaultIRFactory { private final AstIRFactory<T> astFactory; public AstDefaultIRFactory() { this(new AstIRFactory<>()); } public AstDefaultIRFactory(AstIRFactory<T> astFactory) { this.astFactory = astFactory; } @Override public IR makeIR(IMethod method, Context context, SSAOptions options) { if (method instanceof AstMethod) { return astFactory.makeIR(method, context, options); } else { return super.makeIR(method, context, options); } } @Override public ControlFlowGraph<?, ?> makeCFG(IMethod method, Context context) { if (method instanceof AstMethod) { return astFactory.makeCFG(method); } else { return super.makeCFG(method, context); } } } public static class AstIR extends IR { private final LexicalInformation lexicalInfo; private final SSAConversion.SSAInformation localMap; public LexicalInformation lexicalInfo() { return lexicalInfo; } private void setCatchInstructions(SSACFG ssacfg, AbstractCFG<?, ?> oldcfg) { for (int i = 0; i < oldcfg.getNumberOfNodes(); i++) if (oldcfg.isCatchBlock(i)) { ExceptionHandlerBasicBlock B = (ExceptionHandlerBasicBlock) ssacfg.getNode(i); B.setCatchInstruction( (SSAGetCaughtExceptionInstruction) getInstructions()[B.getFirstInstructionIndex()]); getInstructions()[B.getFirstInstructionIndex()] = null; } else { assert !(ssacfg.getNode(i) instanceof ExceptionHandlerBasicBlock); } } private static void setupCatchTypes( SSACFG cfg, Map<IBasicBlock<SSAInstruction>, TypeReference[]> map) { for (Entry<IBasicBlock<SSAInstruction>, TypeReference[]> e : map.entrySet()) { if (e.getKey().getNumber() != -1) { ExceptionHandlerBasicBlock bb = (ExceptionHandlerBasicBlock) cfg.getNode(e.getKey().getNumber()); for (int j = 0; j < e.getValue().length; j++) { bb.addCaughtExceptionType(e.getValue()[j]); } } } } @Override public SSAInformation getLocalMap() { return localMap; } @Override protected String instructionPosition(int instructionIndex) { Position pos = getMethod().getSourcePosition(instructionIndex); if (pos == null) { return ""; } else { return pos.toString(); } } @Override public AstMethod getMethod() { return (AstMethod) super.getMethod(); } private AstIR( AstMethod method, SSAInstruction[] instructions, SymbolTable symbolTable, SSACFG cfg, SSAOptions options) { super(method, instructions, symbolTable, cfg, options); lexicalInfo = method.cloneLexicalInfo(); setCatchInstructions(getControlFlowGraph(), method.cfg()); localMap = SSAConversion.convert(method, this, options); setupCatchTypes(getControlFlowGraph(), method.catchTypes()); setupLocationMap(); } @Override protected SSAIndirectionData<Name> getIndirectionData() { // TODO Auto-generated method stub return null; } } @Override public IR makeIR(final IMethod method, final Context context, final SSAOptions options) { assert method instanceof AstMethod : method.toString(); AbstractCFG<?, ?> oldCfg = ((AstMethod) method).cfg(); SSAInstruction[] oldInstrs = (SSAInstruction[]) oldCfg.getInstructions(); SSAInstruction[] instrs = oldInstrs.clone(); IR newIR = new AstIR( (AstMethod) method, instrs, ((AstMethod) method).symbolTable().copy(), new SSACFG(method, oldCfg, instrs), options); return newIR; } public static IRFactory<IMethod> makeDefaultFactory() { return new AstDefaultIRFactory<>(); } @Override public boolean contextIsIrrelevant(IMethod method) { return true; } }
5,634
30.132597
98
java
WALA
WALA-master/cast/src/main/java/com/ibm/wala/cast/ir/ssa/AstInstructionFactory.java
/* * Copyright (c) 2009 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.cast.ir.ssa; import com.ibm.wala.cast.ir.ssa.AstLexicalAccess.Access; import com.ibm.wala.ssa.SSAInstructionFactory; import com.ibm.wala.types.FieldReference; import com.ibm.wala.types.TypeReference; public interface AstInstructionFactory extends SSAInstructionFactory { AssignInstruction AssignInstruction(int iindex, int result, int val); AstAssertInstruction AssertInstruction(int iindex, int value, boolean fromSpecification); AstEchoInstruction EchoInstruction(int iindex, int[] rvals); AstGlobalRead GlobalRead(int iindex, int lhs, FieldReference global); AstGlobalWrite GlobalWrite(int iindex, FieldReference global, int rhs); AstIsDefinedInstruction IsDefinedInstruction( int iindex, int lval, int rval, int fieldVal, FieldReference fieldRef); AstIsDefinedInstruction IsDefinedInstruction( int iindex, int lval, int rval, FieldReference fieldRef); AstIsDefinedInstruction IsDefinedInstruction(int iindex, int lval, int rval, int fieldVal); AstIsDefinedInstruction IsDefinedInstruction(int iindex, int lval, int rval); AstLexicalRead LexicalRead(int iindex, Access[] accesses); AstLexicalRead LexicalRead(int iindex, Access access); AstLexicalRead LexicalRead( int iindex, int lhs, String definer, String globalName, TypeReference type); AstLexicalWrite LexicalWrite(int iindex, Access[] accesses); AstLexicalWrite LexicalWrite(int iindex, Access access); AstLexicalWrite LexicalWrite( int iindex, String definer, String globalName, TypeReference type, int rhs); EachElementGetInstruction EachElementGetInstruction( int iindex, int lValue, int objectRef, int previousProp); EachElementHasNextInstruction EachElementHasNextInstruction( int iindex, int lValue, int objectRef, int previousProp); AstPropertyRead PropertyRead(int iindex, int result, int objectRef, int memberRef); AstPropertyWrite PropertyWrite(int iindex, int objectRef, int memberRef, int value); AstYieldInstruction YieldInstruction(int iindex, int[] rvals); }
2,421
35.69697
93
java
WALA
WALA-master/cast/src/main/java/com/ibm/wala/cast/ir/ssa/AstInstructionVisitor.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.cast.ir.ssa; import com.ibm.wala.ssa.SSAInstruction; @SuppressWarnings("unused") public interface AstInstructionVisitor extends SSAInstruction.IVisitor { default void visitAstLexicalRead(AstLexicalRead instruction) {} default void visitAstLexicalWrite(AstLexicalWrite instruction) {} default void visitAstGlobalRead(AstGlobalRead instruction) {} default void visitAstGlobalWrite(AstGlobalWrite instruction) {} default void visitAssert(AstAssertInstruction instruction) {} default void visitEachElementGet(EachElementGetInstruction inst) {} default void visitEachElementHasNext(EachElementHasNextInstruction inst) {} default void visitIsDefined(AstIsDefinedInstruction inst) {} default void visitEcho(AstEchoInstruction inst) {} default void visitYield(AstYieldInstruction inst) {} default void visitPropertyRead(AstPropertyRead instruction) {} default void visitPropertyWrite(AstPropertyWrite instruction) {} }
1,345
31.047619
77
java
WALA
WALA-master/cast/src/main/java/com/ibm/wala/cast/ir/ssa/AstIsDefinedInstruction.java
/* * Copyright (c) 2013 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.cast.ir.ssa; import com.ibm.wala.ssa.SSAInstruction; import com.ibm.wala.ssa.SSAInstructionFactory; import com.ibm.wala.ssa.SymbolTable; import com.ibm.wala.types.FieldReference; import com.ibm.wala.types.TypeReference; import com.ibm.wala.util.debug.Assertions; import java.util.Collection; import java.util.Collections; /** * IR instruction to check whether a field is defined on some object. The field is represented * either by a {@link FieldReference} or by a local value number. */ public class AstIsDefinedInstruction extends SSAInstruction { /** name of the field. If non-null, fieldVal should be -1. */ private final FieldReference fieldRef; /** value number holding the field string. If non-negative, fieldRef should be null. */ private final int fieldVal; /** the base pointer */ private final int rval; /** gets 1 if the field is defined, 0 otherwise. */ private final int lval; /** * This constructor should only be used from {@link * SSAInstruction#copyForSSA(SSAInstructionFactory, int[], int[])} */ public AstIsDefinedInstruction( int iindex, int lval, int rval, int fieldVal, FieldReference fieldRef) { super(iindex); this.lval = lval; this.rval = rval; this.fieldVal = fieldVal; this.fieldRef = fieldRef; } public AstIsDefinedInstruction(int iindex, int lval, int rval, FieldReference fieldRef) { super(iindex); this.lval = lval; this.rval = rval; this.fieldVal = -1; this.fieldRef = fieldRef; } public AstIsDefinedInstruction(int iindex, int lval, int rval, int fieldVal) { super(iindex); this.lval = lval; this.rval = rval; this.fieldVal = fieldVal; this.fieldRef = null; } public AstIsDefinedInstruction(int iindex, int lval, int rval) { super(iindex); this.lval = lval; this.rval = rval; this.fieldVal = -1; this.fieldRef = null; } @Override public SSAInstruction copyForSSA(SSAInstructionFactory insts, int[] defs, int[] uses) { assert fieldVal == -1 || fieldRef == null; return ((AstInstructionFactory) insts) .IsDefinedInstruction( iIndex(), (defs == null) ? lval : defs[0], (uses == null) ? rval : uses[0], (uses == null || fieldVal == -1) ? fieldVal : uses[1], fieldRef); } @Override public String toString(SymbolTable symbolTable) { if (fieldVal == -1 && fieldRef == null) { return getValueString(symbolTable, lval) + " = isDefined(" + getValueString(symbolTable, rval) + ')'; } else if (fieldVal == -1) { return getValueString(symbolTable, lval) + " = isDefined(" + getValueString(symbolTable, rval) + ',' + fieldRef.getName() + ')'; } else if (fieldRef == null) { return getValueString(symbolTable, lval) + " = isDefined(" + getValueString(symbolTable, rval) + ',' + getValueString(symbolTable, fieldVal) + ')'; } else { Assertions.UNREACHABLE(); return null; } } @Override public void visit(IVisitor v) { ((AstInstructionVisitor) v).visitIsDefined(this); } @Override public Collection<TypeReference> getExceptionTypes() { return Collections.emptySet(); } @Override public boolean hasDef() { return true; } @Override public int getDef() { return lval; } @Override public int getDef(int i) { assert i == 0; return lval; } @Override public int getNumberOfDefs() { return 1; } @Override public int getNumberOfUses() { return (fieldVal == -1) ? 1 : 2; } @Override public int getUse(int j) { if (j == 0) { return rval; } else if (j == 1 && fieldVal != -1) { return fieldVal; } else { Assertions.UNREACHABLE(); return -1; } } @Override public boolean isFallThrough() { return true; } @Override public int hashCode() { return 3077 * fieldVal * rval; } public FieldReference getFieldRef() { return fieldRef; } }
4,495
24.117318
94
java
WALA
WALA-master/cast/src/main/java/com/ibm/wala/cast/ir/ssa/AstLexicalAccess.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.cast.ir.ssa; import com.ibm.wala.ssa.SSAInstruction; import com.ibm.wala.types.TypeReference; import com.ibm.wala.util.collections.Pair; import java.util.Collection; import java.util.Objects; /** * This abstract class provides helper functionality for recording lexical uses and/or definitions. * It is used in lexical read and write instructions * * @author Julian Dolby (dolby@us.ibm.com) */ public abstract class AstLexicalAccess extends SSAInstruction { /** * A single lexical access. * * @author Julian Dolby (dolby@us.ibm.com) */ public static class Access { /** name being accessed */ public final String variableName; /** name of entity that defines the variable */ public final String variableDefiner; /** type of the lexical value */ public final TypeReference type; /** value number used for name where access is being performed (not in the declaring entity) */ public final int valueNumber; public Access(String name, String definer, TypeReference type, int vn) { variableName = name; variableDefiner = definer; this.type = type; valueNumber = vn; } public Pair<String, String> getName() { return Pair.make(variableName, variableDefiner); } @Override public int hashCode() { return variableName.hashCode() * valueNumber; } @Override public boolean equals(Object other) { return (other instanceof Access) && variableName.equals(((Access) other).variableName) && valueNumber == ((Access) other).valueNumber && Objects.equals(variableDefiner, ((Access) other).variableDefiner); } @Override public String toString() { return "Access(" + variableName + '@' + variableDefiner + ':' + valueNumber + ')'; } } private Access[] accesses; AstLexicalAccess(int iindex, Access[] accesses) { super(iindex); setAccesses(accesses); } public void setAccesses(Access[] accesses) { this.accesses = accesses; } public Access[] getAccesses() { return accesses; } public Access getAccess(int i) { return accesses[i]; } public int getAccessCount() { return accesses.length; } @Override public boolean isFallThrough() { return true; } @Override public Collection<TypeReference> getExceptionTypes() { return null; } @Override public int hashCode() { int v = 1; for (Access accesse : accesses) v *= accesse.variableName.hashCode(); return v; } }
2,915
24.80531
99
java
WALA
WALA-master/cast/src/main/java/com/ibm/wala/cast/ir/ssa/AstLexicalRead.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.cast.ir.ssa; import com.ibm.wala.ssa.SSAInstruction; import com.ibm.wala.ssa.SSAInstructionFactory; import com.ibm.wala.ssa.SymbolTable; import com.ibm.wala.types.TypeReference; /** * A set of lexical reads. This instruction represents reads of a set of variables that are defined * by a pair of variable name and defining code body (i.e. a method or function). This instruction * has one local value number definition for each lexical read, and the call graph builder ensures * that these value numbers are kept consistent as lexical uses and definitions are discovered * during call graph construction. * * @author Julian Dolby (dolby@us.ibm.com) */ public class AstLexicalRead extends AstLexicalAccess { public AstLexicalRead(int iindex, Access[] accesses) { super(iindex, accesses); } public AstLexicalRead(int iindex, Access access) { this(iindex, new Access[] {access}); } public AstLexicalRead( int iindex, int lhs, String definer, String globalName, TypeReference type) { this(iindex, new Access(globalName, definer, type, lhs)); } @Override public SSAInstruction copyForSSA(SSAInstructionFactory insts, int[] defs, int[] uses) { if (defs == null) { return new AstLexicalRead(iIndex(), getAccesses()); } else { Access[] accesses = new Access[getAccessCount()]; for (int i = 0; i < accesses.length; i++) { Access oldAccess = getAccess(i); accesses[i] = new Access(oldAccess.variableName, oldAccess.variableDefiner, oldAccess.type, defs[i]); } return ((AstInstructionFactory) insts).LexicalRead(iIndex(), accesses); } } @Override public int getNumberOfDefs() { return getAccessCount(); } @Override public int getDef(int i) { return getAccess(i).valueNumber; } @Override public int getNumberOfUses() { return 0; } @Override public int getUse(int i) { throw new UnsupportedOperationException(); } @Override public String toString(SymbolTable symbolTable) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < getAccessCount(); i++) { Access A = getAccess(i); if (i != 0) sb.append(", "); sb.append(getValueString(symbolTable, A.valueNumber)); sb.append(" = lexical:"); sb.append(A.variableName); sb.append('@'); sb.append(A.variableDefiner); } return sb.toString(); } @Override public void visit(IVisitor v) { assert v instanceof AstInstructionVisitor; ((AstInstructionVisitor) v).visitAstLexicalRead(this); } }
2,966
28.67
99
java
WALA
WALA-master/cast/src/main/java/com/ibm/wala/cast/ir/ssa/AstLexicalWrite.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.cast.ir.ssa; import com.ibm.wala.ssa.SSAInstruction; import com.ibm.wala.ssa.SSAInstructionFactory; import com.ibm.wala.ssa.SymbolTable; import com.ibm.wala.types.TypeReference; /** * A set of lexical writes. This instruction represents writes of a set of variables that are * defined by a pair of variable name and defining code body (i.e. a method or function). This * instruction has one local value number use for each lexical write, and the call graph builder * ensures that these value numbers are kept consistent as lexical uses and definitions are * discovered during call graph construction. * * @author Julian Dolby (dolby@us.ibm.com) */ public class AstLexicalWrite extends AstLexicalAccess { public AstLexicalWrite( int iindex, String definer, String globalName, TypeReference type, int rhs) { this(iindex, new Access(globalName, definer, type, rhs)); } public AstLexicalWrite(int iindex, Access access) { this(iindex, new Access[] {access}); } public AstLexicalWrite(int iindex, Access[] accesses) { super(iindex, accesses); } @Override public SSAInstruction copyForSSA(SSAInstructionFactory insts, int[] defs, int[] uses) { if (uses == null) { return new AstLexicalWrite(iIndex(), getAccesses()); } else { Access[] accesses = new Access[getAccessCount()]; for (int i = 0; i < accesses.length; i++) { Access oldAccess = getAccess(i); accesses[i] = new Access(oldAccess.variableName, oldAccess.variableDefiner, oldAccess.type, uses[i]); } return ((AstInstructionFactory) insts).LexicalWrite(iIndex(), accesses); } } @Override public int getNumberOfUses() { return getAccessCount(); } @Override public int getUse(int i) { return getAccess(i).valueNumber; } @Override public int getNumberOfDefs() { return 0; } @Override public int getDef(int i) { throw new UnsupportedOperationException(); } @Override public String toString(SymbolTable symbolTable) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < getAccessCount(); i++) { Access A = getAccess(i); if (i != 0) sb.append(", "); sb.append("lexical:"); sb.append(A.variableName); sb.append('@'); sb.append(A.variableDefiner); sb.append(" = "); sb.append(getValueString(symbolTable, A.valueNumber)); } return sb.toString(); } @Override public void visit(IVisitor v) { assert v instanceof AstInstructionVisitor; ((AstInstructionVisitor) v).visitAstLexicalWrite(this); } }
2,990
28.613861
99
java
WALA
WALA-master/cast/src/main/java/com/ibm/wala/cast/ir/ssa/AstPreInstructionVisitor.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.cast.ir.ssa; public interface AstPreInstructionVisitor extends AstInstructionVisitor { void visitAssign(AssignInstruction inst); }
531
30.294118
73
java
WALA
WALA-master/cast/src/main/java/com/ibm/wala/cast/ir/ssa/AstPropertyRead.java
package com.ibm.wala.cast.ir.ssa; import com.ibm.wala.ssa.SSAInstruction; import com.ibm.wala.ssa.SSAInstructionFactory; public abstract class AstPropertyRead extends AbstractReflectiveGet { public AstPropertyRead(int iindex, int result, int objectRef, int memberRef) { super(iindex, result, objectRef, memberRef); } @Override public SSAInstruction copyForSSA(SSAInstructionFactory insts, int[] defs, int[] uses) { return ((AstInstructionFactory) insts) .PropertyRead( iIndex(), defs == null ? getDef() : defs[0], uses == null ? getObjectRef() : uses[0], uses == null ? getMemberRef() : uses[1]); } @Override public boolean isPEI() { return true; } /** * /* (non-Javadoc) * * @see com.ibm.wala.ssa.SSAInstruction#visit(com.ibm.wala.ssa.SSAInstruction.IVisitor) */ @Override public void visit(IVisitor v) { assert v instanceof AstInstructionVisitor; ((AstInstructionVisitor) v).visitPropertyRead(this); } }
1,024
25.973684
89
java
WALA
WALA-master/cast/src/main/java/com/ibm/wala/cast/ir/ssa/AstPropertyWrite.java
package com.ibm.wala.cast.ir.ssa; import com.ibm.wala.ssa.SSAInstruction; import com.ibm.wala.ssa.SSAInstructionFactory; import com.ibm.wala.ssa.SymbolTable; public abstract class AstPropertyWrite extends AbstractReflectivePut { public AstPropertyWrite(int iindex, int objectRef, int memberRef, int value) { super(iindex, objectRef, memberRef, value); } @Override public SSAInstruction copyForSSA(SSAInstructionFactory insts, int[] defs, int[] uses) { return ((AstInstructionFactory) insts) .PropertyWrite( iIndex(), uses == null ? getObjectRef() : uses[0], uses == null ? getMemberRef() : uses[1], uses == null ? getValue() : uses[2]); } @Override public String toString(SymbolTable symbolTable) { return super.toString(symbolTable) + " = " + getValueString(symbolTable, getValue()); } /** @see com.ibm.wala.ssa.SSAInstruction#visit(IVisitor) */ @Override public void visit(IVisitor v) { assert v instanceof AstInstructionVisitor; ((AstInstructionVisitor) v).visitPropertyWrite(this); } @Override public boolean isPEI() { return true; } }
1,157
27.95
89
java
WALA
WALA-master/cast/src/main/java/com/ibm/wala/cast/ir/ssa/AstYieldInstruction.java
/* * Copyright (c) 2013 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.cast.ir.ssa; import com.ibm.wala.ssa.SSAInstruction; import com.ibm.wala.ssa.SSAInstructionFactory; import com.ibm.wala.ssa.SymbolTable; public class AstYieldInstruction extends AstConsumeInstruction { public AstYieldInstruction(int iindex, int[] rvals) { super(iindex, rvals); } @Override public SSAInstruction copyForSSA(SSAInstructionFactory insts, int[] defs, int[] uses) { return ((AstInstructionFactory) insts).EchoInstruction(iIndex(), uses == null ? rvals : uses); } @Override public String toString(SymbolTable symbolTable) { StringBuilder result = new StringBuilder("echo/print "); for (int rval : rvals) { result.append(getValueString(symbolTable, rval)).append(' '); } return result.toString(); } @Override public void visit(IVisitor v) { ((AstInstructionVisitor) v).visitYield(this); } }
1,253
28.162791
98
java
WALA
WALA-master/cast/src/main/java/com/ibm/wala/cast/ir/ssa/CAstBinaryOp.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.cast.ir.ssa; import com.ibm.wala.shrike.shrikeBT.IBinaryOpInstruction; public enum CAstBinaryOp implements IBinaryOpInstruction.IOperator { CONCAT, EQ, NE, LT, GE, GT, LE, STRICT_EQ, STRICT_NE; @Override public String toString() { return super.toString().toLowerCase(); } }
701
21.645161
72
java
WALA
WALA-master/cast/src/main/java/com/ibm/wala/cast/ir/ssa/CAstUnaryOp.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.cast.ir.ssa; import com.ibm.wala.shrike.shrikeBT.IUnaryOpInstruction; public enum CAstUnaryOp implements IUnaryOpInstruction.IOperator { MINUS, BITNOT, PLUS; @Override public String toString() { return super.toString().toLowerCase(); } }
653
25.16
72
java
WALA
WALA-master/cast/src/main/java/com/ibm/wala/cast/ir/ssa/EachElementGetInstruction.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.cast.ir.ssa; import com.ibm.wala.ssa.SSAAbstractBinaryInstruction; import com.ibm.wala.ssa.SSAInstruction; import com.ibm.wala.ssa.SSAInstructionFactory; import com.ibm.wala.ssa.SymbolTable; import com.ibm.wala.types.TypeReference; import java.util.Collection; import java.util.Collections; /** * This instruction represents iterating through the properties of its receiver object. The use * represents an object, and the l-value represents one of a sequence of property names, suitable * for use with the appropriate AbstractReflectiveGet sub-class. * * <p>Iterating across the fields or properties of a given object is a common idiom in scripting * languages, which is why the IR has first-class support for it. * * @author Julian Dolby (dolby@us.ibm.com) */ public class EachElementGetInstruction extends SSAAbstractBinaryInstruction { public EachElementGetInstruction(int iindex, int lValue, int objectRef, int previousProp) { super(iindex, lValue, objectRef, previousProp); } @Override public SSAInstruction copyForSSA(SSAInstructionFactory insts, int[] defs, int[] uses) { return ((AstInstructionFactory) insts) .EachElementGetInstruction( iIndex(), (defs == null) ? getDef(0) : defs[0], (uses == null) ? getUse(0) : uses[0], (uses == null) ? getUse(1) : uses[1]); } @Override public String toString(SymbolTable symbolTable) { return getValueString(symbolTable, getDef(0)) + " = a property name of " + getValueString(symbolTable, getUse(0)); } @Override public void visit(IVisitor v) { ((AstInstructionVisitor) v).visitEachElementGet(this); } @Override public Collection<TypeReference> getExceptionTypes() { return Collections.emptySet(); } @Override public boolean isFallThrough() { return true; } @Override public boolean isPEI() { return true; } }
2,311
30.243243
97
java
WALA
WALA-master/cast/src/main/java/com/ibm/wala/cast/ir/ssa/EachElementHasNextInstruction.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.cast.ir.ssa; import com.ibm.wala.ssa.SSAAbstractBinaryInstruction; import com.ibm.wala.ssa.SSAInstruction; import com.ibm.wala.ssa.SSAInstructionFactory; import com.ibm.wala.ssa.SymbolTable; import com.ibm.wala.types.TypeReference; import java.util.Collection; import java.util.Collections; /** * This instruction represents iterating through the properties of its receiver object. The use * represents an object, and the l-value represents a boolean indicating whether the object has more * properties. * * <p>Iterating across the fields or properties of a given object is a common idiom in scripting * languages, which is why the IR has first-class support for it. * * @author Julian Dolby (dolby@us.ibm.com) */ public class EachElementHasNextInstruction extends SSAAbstractBinaryInstruction { public EachElementHasNextInstruction(int iindex, int lValue, int objectRef, int previousPropVal) { super(iindex, lValue, objectRef, previousPropVal); } @Override public SSAInstruction copyForSSA(SSAInstructionFactory insts, int[] defs, int[] uses) { return ((AstInstructionFactory) insts) .EachElementHasNextInstruction( iIndex(), (defs == null) ? getDef(0) : defs[0], (uses == null) ? getUse(0) : uses[0], (uses == null) ? getUse(1) : uses[1]); } @Override public String toString(SymbolTable symbolTable) { return getValueString(symbolTable, getDef(0)) + " = has next property: " + getValueString(symbolTable, getUse(0)); } @Override public void visit(IVisitor v) { ((AstInstructionVisitor) v).visitEachElementHasNext(this); } @Override public Collection<TypeReference> getExceptionTypes() { return Collections.emptySet(); } @Override public boolean isFallThrough() { return true; } }
2,225
31.26087
100
java
WALA
WALA-master/cast/src/main/java/com/ibm/wala/cast/ir/ssa/FixedParametersInvokeInstruction.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.cast.ir.ssa; import com.ibm.wala.classLoader.CallSiteReference; import com.ibm.wala.ssa.SSAInstruction; import com.ibm.wala.ssa.SSAInstructionFactory; /** * This abstract instruction extends the abstract invoke with functionality to support invocations * with a fixed number of arguments---the only case in some languages and a common case even in * scripting languages. * * @author Julian Dolby (dolby@us.ibm.com) */ public abstract class FixedParametersInvokeInstruction extends MultiReturnValueInvokeInstruction { /** * The value numbers of the arguments passed to the call. For non-static methods, params[0] == * this. If params == null, this should be a static method with no parameters. */ private final int[] params; public FixedParametersInvokeInstruction( int iindex, int results[], int[] params, int exception, CallSiteReference site) { super(iindex, results, exception, site); this.params = params; } public FixedParametersInvokeInstruction( int iindex, int result, int[] params, int exception, CallSiteReference site) { this(iindex, new int[] {result}, params, exception, site); } /** Constructor InvokeInstruction. This case for void return values */ public FixedParametersInvokeInstruction( int iindex, int[] params, int exception, CallSiteReference site) { this(iindex, null, params, exception, site); } protected abstract SSAInstruction copyInstruction( SSAInstructionFactory insts, int result[], int[] params, int exception); @Override public SSAInstruction copyForSSA(SSAInstructionFactory insts, int[] defs, int[] uses) { int newParams[] = params; if (uses != null) { int i = 0; newParams = new int[params.length]; for (int j = 0; j < newParams.length; j++) newParams[j] = uses[i++]; } int newLvals[] = null; if (getNumberOfReturnValues() > 0) { newLvals = results.clone(); } int newExp = exception; if (defs != null) { int i = 0; if (getNumberOfReturnValues() > 0) { newLvals[0] = defs[i++]; } newExp = defs[i++]; for (int j = 1; j < getNumberOfReturnValues(); j++) { newLvals[j] = defs[i++]; } } return copyInstruction(insts, newLvals, newParams, newExp); } @Override public int getNumberOfPositionalParameters() { if (params == null) { return 0; } else { return params.length; } } @Override public void visit(IVisitor v) { // TODO Auto-generated method stub assert false; } @Override public int getNumberOfUses() { return getNumberOfPositionalParameters(); } @Override public int hashCode() { // TODO Auto-generated method stub assert false; return 0; } @Override public int getUse(int j) { if (j < getNumberOfPositionalParameters()) return params[j]; else { return super.getUse(j); } } }
3,318
27.127119
98
java
WALA
WALA-master/cast/src/main/java/com/ibm/wala/cast/ir/ssa/MultiReturnValueInvokeInstruction.java
/* * Copyright (c) 2013 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.cast.ir.ssa; import com.ibm.wala.classLoader.CallSiteReference; import com.ibm.wala.ssa.SSAAbstractInvokeInstruction; public abstract class MultiReturnValueInvokeInstruction extends SSAAbstractInvokeInstruction { protected final int results[]; protected MultiReturnValueInvokeInstruction( int iindex, int results[], int exception, CallSiteReference site) { super(iindex, exception, site); this.results = results; } @Override public int getNumberOfReturnValues() { return results == null ? 0 : results.length; } @Override public int getReturnValue(int i) { return results == null ? -1 : results[i]; } }
1,036
28.628571
94
java
WALA
WALA-master/cast/src/main/java/com/ibm/wala/cast/ir/ssa/SSAConversion.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.cast.ir.ssa; import com.ibm.wala.cast.ir.ssa.analysis.LiveAnalysis; import com.ibm.wala.cast.loader.AstMethod; import com.ibm.wala.cast.loader.AstMethod.DebuggingInformation; import com.ibm.wala.cast.loader.AstMethod.LexicalInformation; import com.ibm.wala.ssa.SSACFG; import com.ibm.wala.ssa.SSAInstruction; import com.ibm.wala.ssa.SSAOptions; import com.ibm.wala.ssa.SSAPhiInstruction; import com.ibm.wala.ssa.SymbolTable; import com.ibm.wala.util.collections.HashMapFactory; import com.ibm.wala.util.collections.HashSetFactory; import com.ibm.wala.util.collections.IteratorUtil; import com.ibm.wala.util.intset.BitVector; import com.ibm.wala.util.intset.BitVectorIntSet; import com.ibm.wala.util.intset.IntSet; import com.ibm.wala.util.intset.IntSetUtil; import com.ibm.wala.util.intset.MutableIntSet; import java.util.ArrayList; import java.util.Arrays; import java.util.Map; import java.util.Set; /** * @author Julian Dolby * <p>Standard SSA conversion for local value numbers. */ public class SSAConversion extends AbstractSSAConversion { public static boolean DEBUG = false; public static boolean DEBUG_UNDO = false; public static boolean DEBUG_NAMES = false; public static boolean DUMP = false; private final AstIRFactory.AstIR ir; private int nextSSAValue; private final DebuggingInformation debugInfo; private final LexicalInformation lexicalInfo; private final SymbolTable symtab; private final LiveAnalysis.Result liveness; private SSAInformation computedLocalMap; private final Map<Integer, Integer> assignments = HashMapFactory.make(); // // Copy propagation history // private final Map<Object, CopyPropagationRecord> copyPropagationMap; private final ArrayList<CopyPropagationRecord> R[]; public static class UseRecord { final int instructionIndex; final int useNumber; public int getInstructionIndex() { return instructionIndex; } public int getUseNumber() { return useNumber; } private UseRecord(int instructionIndex, int useNumber) { this.useNumber = useNumber; this.instructionIndex = instructionIndex; } @Override public String toString() { return "[use " + useNumber + " of " + instructionIndex + ']'; } @Override public int hashCode() { return useNumber * instructionIndex; } @Override public boolean equals(Object o) { return (o instanceof UseRecord) && instructionIndex == ((UseRecord) o).instructionIndex && useNumber == ((UseRecord) o).useNumber; } } public static class PhiUseRecord { final int BBnumber; final int phiNumber; final int useNumber; private PhiUseRecord(int BBnumber, int phiNumber, int useNumber) { this.BBnumber = BBnumber; this.phiNumber = phiNumber; this.useNumber = useNumber; } public int getBBnumber() { return BBnumber; } public int getPhiNumber() { return phiNumber; } public int getUseNumber() { return useNumber; } @Override public String toString() { return "[use " + useNumber + " of " + phiNumber + " of block " + BBnumber + ']'; } @Override public int hashCode() { return phiNumber * BBnumber * useNumber; } @Override public boolean equals(Object o) { return (o instanceof PhiUseRecord) && BBnumber == ((PhiUseRecord) o).BBnumber && phiNumber == ((PhiUseRecord) o).phiNumber && useNumber == ((PhiUseRecord) o).useNumber; } } public class CopyPropagationRecord { final int rhs; final int instructionIndex; final Set<Object> renamedUses = HashSetFactory.make(2); private final Set<CopyPropagationRecord> childRecords = HashSetFactory.make(1); public int getRhs() { return rhs; } public int getInstructionIndex() { return instructionIndex; } public Set<Object> getRenamedUses() { return renamedUses; } public Set<CopyPropagationRecord> getChildRecords() { return childRecords; } @Override public String toString() { StringBuilder sb = new StringBuilder("<vn " + rhs + " at " + instructionIndex); for (CopyPropagationRecord c : childRecords) { sb.append("\n ").append(c.toString()); } sb.append('>'); return sb.toString(); } @Override public int hashCode() { return instructionIndex; } @Override public boolean equals(Object o) { return (o instanceof CopyPropagationRecord) && instructionIndex == ((CopyPropagationRecord) o).instructionIndex; } private CopyPropagationRecord(int instructionIndex, int rhs) { if (DEBUG_UNDO) System.err.println( ("new copy record for instruction #" + instructionIndex + ", rhs value is " + rhs)); this.rhs = rhs; this.instructionIndex = instructionIndex; } private void addChild(CopyPropagationRecord rec) { if (DEBUG_UNDO) System.err.println( ("(" + rec.instructionIndex + ',' + rec.rhs + ") is a child of (" + instructionIndex + ',' + rhs + ')')); childRecords.add(rec); } private void addUse(int instructionIndex, int use) { if (DEBUG_UNDO) System.err.println( ("propagated use of (" + this.instructionIndex + ',' + this.rhs + ") at use #" + use + " of instruction #" + instructionIndex)); UseRecord rec = new UseRecord(instructionIndex, use); copyPropagationMap.put(rec, this); renamedUses.add(rec); } private void addUse(int BB, int phiNumber, int use) { PhiUseRecord rec = new PhiUseRecord(BB, phiNumber, use); copyPropagationMap.put(rec, this); renamedUses.add(rec); } private SSAInstruction undo(SSAInstruction inst, int use, int val) { int c = getNumberOfUses(inst); int[] newUses = new int[c]; for (int i = 0; i < c; i++) { if (i == use) newUses[i] = val; else newUses[i] = getUse(inst, i); } return inst.copyForSSA( CFG.getMethod().getDeclaringClass().getClassLoader().getInstructionFactory(), null, newUses); } private void undo(int rhs) { int lhs = symtab.newSymbol(); instructions[instructionIndex] = new AssignInstruction(instructionIndex, lhs, rhs); if (DEBUG_UNDO) System.err.println( ("recreating assignment at " + instructionIndex + " as " + lhs + " = " + rhs)); for (Object x : renamedUses) { if (x instanceof UseRecord) { UseRecord use = (UseRecord) x; int idx = use.instructionIndex; SSAInstruction inst = instructions[idx]; if (DEBUG_UNDO) System.err.println( ("Changing use #" + use.useNumber + " of inst #" + idx + " to val " + lhs)); if (use.useNumber >= 0) { instructions[idx] = undo(inst, use.useNumber, lhs); } else { lexicalInfo.getExposedUses(idx)[-use.useNumber - 1] = lhs; } copyPropagationMap.remove(use); } else { PhiUseRecord use = (PhiUseRecord) x; int bb = use.BBnumber; int phi = use.phiNumber; SSACFG.BasicBlock BB = CFG.getNode(bb); BB.addPhiForLocal( phi, (SSAPhiInstruction) undo(BB.getPhiForLocal(phi), use.useNumber, lhs)); copyPropagationMap.remove(use); } } for (CopyPropagationRecord copyPropagationRecord : childRecords) { copyPropagationRecord.undo(lhs); } } public void undo() { undo(this.rhs); copyPropagationMap.remove(new UseRecord(instructionIndex, rhs)); } } public static void undoCopyPropagation(AstIRFactory.AstIR ir, int instruction, int use) { SSAInformation info = ir.getLocalMap(); info.undoCopyPropagation(instruction, use); } public static void copyUse( AstIRFactory.AstIR ir, int fromInst, int fromUse, int toInst, int toUse) { SSAInformation info = ir.getLocalMap(); info.copyUse(fromInst, fromUse, toInst, toUse); } // // SSA2LocalMap implementation for SSAConversion // public class SSAInformation implements com.ibm.wala.ssa.IR.SSA2LocalMap { private final String[][] computedNames = new String[valueMap.length][]; @Override public String[] getLocalNames(int pc, int vn) { if (computedNames[vn] != null) { return computedNames[vn]; } int v = skip(vn) || vn >= valueMap.length ? vn : valueMap[vn]; String[][] namesData = debugInfo.getSourceNamesForValues(); String[] vNames = namesData[v]; Set<String> x = HashSetFactory.make(); x.addAll(Arrays.asList(vNames)); MutableIntSet vals = IntSetUtil.make(); while (assignments.containsKey(v) && !vals.contains(v)) { vals.add(v); v = assignments.get(v); vNames = namesData[v]; x.addAll(Arrays.asList(vNames)); } return computedNames[vn] = x.toArray(new String[0]); } private void undoCopyPropagation(int instructionIndex, int useNumber) { if (DEBUG_UNDO) System.err.println(("undoing for use #" + useNumber + " of inst #" + instructionIndex)); UseRecord use = new UseRecord(instructionIndex, useNumber); if (copyPropagationMap.containsKey(use)) { copyPropagationMap.get(use).undo(); } } private void copyUse(int fromInst, int fromUse, int toInst, int toUse) { UseRecord use = new UseRecord(fromInst, fromUse); if (copyPropagationMap.containsKey(use)) { copyPropagationMap.get(use).addUse(toInst, toUse); } } public Map<Object, CopyPropagationRecord> getCopyHistory() { return copyPropagationMap; } @Override public String toString() { StringBuilder sb = new StringBuilder(super.toString()); for (Map.Entry<Object, CopyPropagationRecord> x : copyPropagationMap.entrySet()) { sb.append(x.getKey().toString()) .append(" --> ") .append(x.getValue().toString()) .append('\n'); } return sb.toString(); } } private CopyPropagationRecord topR(int v) { if (R[v] != null && !R[v].isEmpty()) { CopyPropagationRecord rec = peek(R[v]); if (top(v) == rec.rhs) { return rec; } } return null; } private static <T> void push(ArrayList<T> stack, T elt) { stack.add(elt); } private static <T> T peek(ArrayList<T> stack) { return stack.get(stack.size() - 1); } // // implementation of AbstractSSAConversion hooks // @Override protected int getNumberOfDefs(SSAInstruction inst) { return inst.getNumberOfDefs(); } @Override protected int getDef(SSAInstruction inst, int index) { return inst.getDef(index); } @Override protected int getNumberOfUses(SSAInstruction inst) { return inst.getNumberOfUses(); } @Override protected int getUse(SSAInstruction inst, int index) { return inst.getUse(index); } @Override protected boolean isAssignInstruction(SSAInstruction inst) { return inst instanceof AssignInstruction; } @Override protected int getMaxValueNumber() { return symtab.getMaxValueNumber(); } @Override protected boolean skip(int vn) { return false; } @Override protected boolean isLive(SSACFG.BasicBlock Y, int V) { return liveness.isLiveEntry(Y, V); } private void addPhi(SSACFG.BasicBlock BB, SSAPhiInstruction phi) { BB.addPhiForLocal(phiCounts[BB.getGraphNodeId()], phi); } @Override protected void placeNewPhiAt(int value, SSACFG.BasicBlock Y) { int[] params = new int[CFG.getPredNodeCount(Y)]; Arrays.fill(params, value); SSAPhiInstruction phi = new SSAPhiInstruction(SSAInstruction.NO_INDEX, value, params); if (DEBUG) System.err.println(("Placing " + phi + " at " + Y)); addPhi(Y, phi); } @Override protected SSAPhiInstruction getPhi(SSACFG.BasicBlock B, int index) { return B.getPhiForLocal(index); } @Override protected void setPhi(SSACFG.BasicBlock B, int index, SSAPhiInstruction inst) { B.addPhiForLocal(index, inst); } @Override protected SSAPhiInstruction repairPhiDefs(SSAPhiInstruction phi, int[] newDefs) { return (SSAPhiInstruction) phi.copyForSSA( CFG.getMethod().getDeclaringClass().getClassLoader().getInstructionFactory(), newDefs, null); } @Override protected void repairPhiUse(SSACFG.BasicBlock BB, int phiIndex, int rvalIndex, int newRval) { SSAPhiInstruction phi = getPhi(BB, phiIndex); int[] newUses = new int[getNumberOfUses(phi)]; for (int v = 0; v < newUses.length; v++) { int oldUse = getUse(phi, v); int newUse = (v == rvalIndex) ? newRval : oldUse; newUses[v] = newUse; if (v == rvalIndex && topR(oldUse) != null) { topR(oldUse).addUse(BB.getGraphNodeId(), phiIndex, v); } } phi.setValues(newUses); } @Override protected void pushAssignment(SSAInstruction inst, int index, int newRhs) { int lhs = getDef(inst, 0); int rhs = getUse(inst, 0); assignments.put(rhs, lhs); CopyPropagationRecord rec = new CopyPropagationRecord(index, newRhs); push(R[lhs], rec); if (topR(rhs) != null) { topR(rhs).addChild(rec); } } @Override protected void repairInstructionUses(SSAInstruction inst, int index, int[] newUses) { for (int j = 0; j < getNumberOfUses(inst); j++) { if (topR(getUse(inst, j)) != null) { topR(getUse(inst, j)).addUse(index, j); } } int[] lexicalUses = lexicalInfo.getExposedUses(index); if (lexicalUses != null) { for (int j = 0; j < lexicalUses.length; j++) { int lexicalUse = lexicalUses[j]; if (lexicalUse != -1 && !skip(lexicalUse)) { if (S.length <= lexicalUse || S[lexicalUse].isEmpty()) { lexicalUses[j] = -1; } else { int newUse = top(lexicalUse); lexicalUses[j] = newUse; if (topR(lexicalUse) != null) { topR(lexicalUse).addUse(index, -j - 1); } } } } } } @Override protected void repairInstructionDefs( SSAInstruction inst, int index, int[] newDefs, int[] newUses) { instructions[index] = inst.copyForSSA( CFG.getMethod().getDeclaringClass().getClassLoader().getInstructionFactory(), newDefs, newUses); } @Override protected void popAssignment(SSAInstruction inst, int index) { instructions[index] = null; } @Override protected boolean isConstant(int valueNumber) { return symtab.isConstant(valueNumber); } @Override protected boolean skipRepair(SSAInstruction inst, int index) { if (!super.skipRepair(inst, index)) { return false; } if (index == -1) return true; int[] lexicalUses = lexicalInfo.getExposedUses(index); if (lexicalUses != null) { for (int lexicalUs : lexicalUses) { if (!skip(lexicalUs)) { return false; } } } return true; } @SuppressWarnings("unchecked") private SSAConversion(AstMethod M, AstIRFactory.AstIR ir, SSAOptions options) { super(ir, options); Map<Object, CopyPropagationRecord> m = HashMapFactory.make(); this.copyPropagationMap = (ir.getLocalMap() != null) ? ir.getLocalMap().getCopyHistory() : m; this.ir = ir; this.debugInfo = M.debugInfo(); this.lexicalInfo = ir.lexicalInfo(); this.symtab = ir.getSymbolTable(); this.R = new ArrayList[ir.getSymbolTable().getMaxValueNumber() + 1]; for (int i = 0; i < CFG.getNumberOfNodes(); i++) { SSACFG.BasicBlock bb = CFG.getNode(i); if (bb.hasPhi()) { phiCounts[i] = IteratorUtil.count(bb.iteratePhis()); } } this.nextSSAValue = ir.getNumberOfParameters() + 1; int[] exitLive = lexicalInfo.getExitExposedUses(); BitVector v = new BitVector(); if (exitLive != null) { for (int element : exitLive) { if (element > -1) { v.set(element); } } } this.liveness = LiveAnalysis.perform(CFG, symtab, v); if (DEBUG) { System.err.println(liveness); } } @Override protected int getNextNewValueNumber() { while (symtab.isConstant(nextSSAValue) || skip(nextSSAValue)) ++nextSSAValue; symtab.ensureSymbol(nextSSAValue); int v = nextSSAValue++; return v; } @Override protected void initializeVariables() { for (int V = 1; V <= getMaxValueNumber(); V++) { if (!skip(V)) { R[V] = new ArrayList<>(); } } int[] params = symtab.getParameterValueNumbers(); for (int param : params) { if (!skip(param)) { S[param].push(param); valueMap[param] = param; } } } @Override protected void repairExit() { int[] exitLives = lexicalInfo.getExitExposedUses(); if (exitLives != null) { for (int i = 0; i < exitLives.length; i++) { if (exitLives[i] != -1 && !skip(exitLives[i])) { assert !S[exitLives[i]].isEmpty(); exitLives[i] = top(exitLives[i]); } } } } // // Global control. // @Override protected void fail(int v) { System.err.println("during SSA conversion of the following IR:"); System.err.println(ir); super.fail(v); } public SSAInformation getComputedLocalMap() { return computedLocalMap; } @Override public void perform() { super.perform(); if (DUMP) { System.err.println(ir); if (lexicalInfo != null) { for (int i = 0; i < instructions.length; i++) { int[] lexicalUses = lexicalInfo.getExposedUses(i); if (lexicalUses != null) { System.err.print(("extra uses for " + instructions[i] + ": ")); for (int lexicalUse : lexicalUses) { System.err.print((Integer.valueOf(lexicalUse).toString() + ' ')); } System.err.println(); } } } } computedLocalMap = new SSAInformation(); } private static IntSet valuesToConvert(AstIRFactory.AstIR ir) { SSAInstruction[] insts = ir.getInstructions(); MutableIntSet foundOne = new BitVectorIntSet(); MutableIntSet foundTwo = new BitVectorIntSet(); for (SSAInstruction inst : insts) { if (inst != null) { for (int j = 0; j < inst.getNumberOfDefs(); j++) { int def = inst.getDef(j); if (def != -1) { if (foundOne.contains(def) || ir.getSymbolTable().isConstant(def) || def <= ir.getNumberOfParameters() || inst instanceof AssignInstruction) { foundTwo.add(def); } else { foundOne.add(def); } } } } } return foundTwo; } public static SSAInformation convert(AstMethod M, AstIRFactory.AstIR ir, SSAOptions options) { return convert(M, ir, options, valuesToConvert(ir)); } public static SSAInformation convert( AstMethod M, final AstIRFactory.AstIR ir, SSAOptions options, final IntSet values) { if (DEBUG) { System.err.println(("starting conversion for " + values)); System.err.println(ir); } if (DEBUG_UNDO) System.err.println((">>> starting " + ir.getMethod())); SSAConversion ssa = new SSAConversion(M, ir, options) { final int limit = ir.getSymbolTable().getMaxValueNumber(); @Override protected boolean skip(int i) { return (i >= 0) && (i <= limit) && !values.contains(i); } }; ssa.perform(); if (DEBUG_UNDO) System.err.println(("<<< done " + ir.getMethod())); return ssa.getComputedLocalMap(); } }
20,520
26.581989
97
java
WALA
WALA-master/cast/src/main/java/com/ibm/wala/cast/ir/ssa/analysis/LiveAnalysis.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.cast.ir.ssa.analysis; import com.ibm.wala.cfg.ControlFlowGraph; import com.ibm.wala.core.util.CancelRuntimeException; import com.ibm.wala.dataflow.graph.AbstractMeetOperator; import com.ibm.wala.dataflow.graph.BitVectorSolver; import com.ibm.wala.dataflow.graph.BitVectorUnion; import com.ibm.wala.dataflow.graph.IKilldallFramework; import com.ibm.wala.dataflow.graph.ITransferFunctionProvider; import com.ibm.wala.fixpoint.BitVectorVariable; import com.ibm.wala.fixpoint.UnaryOperator; import com.ibm.wala.ssa.IR; import com.ibm.wala.ssa.ISSABasicBlock; import com.ibm.wala.ssa.SSAInstruction; import com.ibm.wala.ssa.SSAPhiInstruction; import com.ibm.wala.ssa.SymbolTable; import com.ibm.wala.util.CancelException; import com.ibm.wala.util.collections.Iterator2Iterable; import com.ibm.wala.util.debug.Assertions; import com.ibm.wala.util.graph.Graph; import com.ibm.wala.util.graph.impl.GraphInverter; import com.ibm.wala.util.intset.BitVector; import com.ibm.wala.util.intset.BitVectorIntSet; import com.ibm.wala.util.intset.IntSet; /** * @author Julian Dolby * <p>Live-value analysis for a method's IR (or {@link ControlFlowGraph} and {@link * SymbolTable}) using a {@link IKilldallFramework} based implementation. * <p>Pre-requisites - Knowledge of SSA form: control flow graphs, basic blocks, Phi * instructions - Knowledge of <a href="http://en.wikipedia.org/wiki/Data_flow_analysis">data * flow analysis theory</a>. * <p>Implementation notes: * <p>- The solver uses node transfer functions only. - Performance: inverts the CFG to traverse * backwards (backward analysis). */ public class LiveAnalysis { public interface Result { boolean isLiveEntry(ISSABasicBlock bb, int valueNumber); boolean isLiveExit(ISSABasicBlock bb, int valueNumber); BitVector getLiveBefore(int instr); } /** */ public static Result perform(IR ir) { return perform(ir.getControlFlowGraph(), ir.getSymbolTable()); } /** */ public static Result perform( final ControlFlowGraph<SSAInstruction, ISSABasicBlock> cfg, final SymbolTable symtab) { return perform(cfg, symtab, new BitVector()); } /** * @param considerLiveAtExit given set (of variables) to consider to be live after the exit. * <p>todo: used once in {@link com.ibm.wala.cast.ir.ssa.SSAConversion}; Explain better the * purpose. */ public static Result perform( final ControlFlowGraph<SSAInstruction, ISSABasicBlock> cfg, final SymbolTable symtab, final BitVector considerLiveAtExit) { final BitVectorIntSet liveAtExit = new BitVectorIntSet(considerLiveAtExit); final SSAInstruction[] instructions = cfg.getInstructions(); /* Gen/kill operator specific to exit basic blocks */ final class ExitBlockGenKillOperator extends UnaryOperator<BitVectorVariable> { @Override public String toString() { return "ExitGenKill"; } @Override public boolean equals(Object o) { return o == this; } @Override public int hashCode() { return 37721; } /** Evaluate the transfer between two nodes in the flow graph within an exit block. */ @Override public byte evaluate(BitVectorVariable lhs, BitVectorVariable rhs) { boolean changed = lhs.getValue() == null ? !considerLiveAtExit.isZero() : !lhs.getValue().sameValue(liveAtExit); lhs.addAll(considerLiveAtExit); return changed ? CHANGED : NOT_CHANGED; } } /* Gen/kill operator for a regular basic block. */ final class BlockValueGenKillOperator extends UnaryOperator<BitVectorVariable> { private final ISSABasicBlock block; BlockValueGenKillOperator(ISSABasicBlock block) { this.block = block; } @Override public String toString() { return "GenKill:" + block; } @Override public boolean equals(Object o) { return (o instanceof BlockValueGenKillOperator) && ((BlockValueGenKillOperator) o).block.equals(block); } @Override public int hashCode() { return block.hashCode() * 17; } /** Kills the definitions (variables written to). */ private void processDefs(SSAInstruction inst, BitVector bits) { for (int j = 0; j < inst.getNumberOfDefs(); j++) { bits.clear(inst.getDef(j)); } } /** Generates variables that are read (skips constants). */ private void processUses(SSAInstruction inst, BitVector bits) { for (int j = 0; j < inst.getNumberOfUses(); j++) { assert inst.getUse(j) != -1 : inst.toString(); if (!symtab.isConstant(inst.getUse(j))) { bits.set(inst.getUse(j)); } } } /** Evaluate the transfer between two nodes in the flow graph within one basic block. */ @Override public byte evaluate(BitVectorVariable lhs, BitVectorVariable rhs) { // Calculate here the result of the transfer BitVectorIntSet bits = new BitVectorIntSet(); IntSet s = rhs.getValue(); if (s != null) { bits.addAll(s); } // Include all uses generated by the current basic block into the successor's Phi // instructions todo: rephrase for (ISSABasicBlock succBB : Iterator2Iterable.make(cfg.getSuccNodes(block))) { int rval = com.ibm.wala.cast.ir.cfg.Util.whichPred(cfg, succBB, block); for (SSAPhiInstruction sphi : Iterator2Iterable.make(succBB.iteratePhis())) { bits.add(sphi.getUse(rval)); } } // For all instructions, in reverse order, 'kill' variables written to and 'gen' variables // read. for (int i = block.getLastInstructionIndex(); i >= block.getFirstInstructionIndex(); i--) { SSAInstruction inst = instructions[i]; if (inst != null) { processDefs(inst, bits.getBitVector()); processUses(inst, bits.getBitVector()); } } // 'kill' the variables defined by the Phi instructions in the current block. for (SSAInstruction S : Iterator2Iterable.make(block.iteratePhis())) { processDefs(S, bits.getBitVector()); } BitVectorVariable U = new BitVectorVariable(); U.addAll(bits.getBitVector()); if (!lhs.sameValue(U)) { lhs.copyState(U); return CHANGED; } else { return NOT_CHANGED; } } } /* Create the solver */ final BitVectorSolver<ISSABasicBlock> S = new BitVectorSolver<>( new IKilldallFramework<ISSABasicBlock, BitVectorVariable>() { private final Graph<ISSABasicBlock> G = GraphInverter.invert(cfg); @Override public Graph<ISSABasicBlock> getFlowGraph() { return G; } @Override public ITransferFunctionProvider<ISSABasicBlock, BitVectorVariable> getTransferFunctionProvider() { return new ITransferFunctionProvider<>() { @Override public boolean hasNodeTransferFunctions() { return true; } @Override public boolean hasEdgeTransferFunctions() { return false; } /** Create the specialized operator for regular and exit basic blocks. */ @Override public UnaryOperator<BitVectorVariable> getNodeTransferFunction( ISSABasicBlock node) { if (node.isExitBlock()) { return new ExitBlockGenKillOperator(); } else { return new BlockValueGenKillOperator(node); } } @Override public UnaryOperator<BitVectorVariable> getEdgeTransferFunction( ISSABasicBlock s, ISSABasicBlock d) { Assertions.UNREACHABLE(); return null; } /** Live analysis uses 'union' as 'meet operator' */ @Override public AbstractMeetOperator<BitVectorVariable> getMeetOperator() { return BitVectorUnion.instance(); } }; } }); /* Solve the analysis problem */ try { S.solve(null); } catch (CancelException e) { throw new CancelRuntimeException(e); } /* Prepare the lazy result with a closure. */ return new Result() { @Override public String toString() { StringBuilder s = new StringBuilder(); for (int i = 0; i < cfg.getNumberOfNodes(); i++) { ISSABasicBlock bb = cfg.getNode(i); s.append("live entering ").append(bb).append(':').append(S.getOut(bb)).append('\n'); s.append("live exiting ").append(bb).append(':').append(S.getIn(bb)).append('\n'); } return s.toString(); } @Override public boolean isLiveEntry(ISSABasicBlock bb, int valueNumber) { return S.getOut(bb).get(valueNumber); } @Override public boolean isLiveExit(ISSABasicBlock bb, int valueNumber) { return S.getIn(bb).get(valueNumber); } /** * Calculate set of variables live before instruction {@code instr}. * * @see <a href="http://en.wikipedia.org/wiki/Data_flow_analysis#Backward_Analysis">how the * "in" and "out" variable sets work</a> */ @Override public BitVector getLiveBefore(int instr) { ISSABasicBlock bb = cfg.getBlockForInstruction(instr); // Start with the variables live at the 'in' of the basic block of the instruction. todo??? BitVectorIntSet bits = new BitVectorIntSet(); IntSet s = S.getIn(bb).getValue(); if (s != null) { bits.addAll(s); } // For all instructions in the basic block, going backwards, from the last, // up to the desired instruction, 'kill' written variables and 'gen' read variables. for (int i = bb.getLastInstructionIndex(); i >= instr; i--) { SSAInstruction inst = instructions[i]; if (inst != null) { for (int j = 0; j < inst.getNumberOfDefs(); j++) { bits.remove(inst.getDef(j)); } for (int j = 0; j < inst.getNumberOfUses(); j++) { if (!symtab.isConstant(inst.getUse(j))) { bits.add(inst.getUse(j)); } } } } return bits.getBitVector(); } }; } }
11,237
34.22884
100
java
WALA
WALA-master/cast/src/main/java/com/ibm/wala/cast/ir/translator/AbstractClassEntity.java
/* * Copyright (c) 2002 - 2014 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.cast.ir.translator; import com.ibm.wala.cast.tree.CAstQualifier; import com.ibm.wala.cast.tree.CAstType; import java.util.Collection; public abstract class AbstractClassEntity extends AbstractDataEntity { private final CAstType.Class type; public AbstractClassEntity(CAstType.Class type) { this.type = type; } @Override public String toString() { return "class " + type.getName(); } @Override public int getKind() { return TYPE_ENTITY; } @Override public String getName() { return type.getName(); } @Override public CAstType getType() { return type; } @Override public Collection<CAstQualifier> getQualifiers() { return type.getQualifiers(); } }
1,111
21.24
72
java
WALA
WALA-master/cast/src/main/java/com/ibm/wala/cast/ir/translator/AbstractCodeEntity.java
/* * Copyright (c) 2002 - 2014 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.cast.ir.translator; import com.ibm.wala.cast.tree.CAstNode; import com.ibm.wala.cast.tree.CAstSourcePositionMap.Position; import com.ibm.wala.cast.tree.CAstType; import com.ibm.wala.cast.tree.impl.CAstControlFlowRecorder; import com.ibm.wala.cast.tree.impl.CAstNodeTypeMapRecorder; import com.ibm.wala.cast.tree.impl.CAstSourcePositionRecorder; public abstract class AbstractCodeEntity extends AbstractEntity { protected final CAstSourcePositionRecorder src = new CAstSourcePositionRecorder(); protected final CAstControlFlowRecorder cfg = new CAstControlFlowRecorder(src); protected final CAstNodeTypeMapRecorder types = new CAstNodeTypeMapRecorder(); protected final CAstType type; protected CAstNode Ast; protected AbstractCodeEntity(CAstType type) { this.type = type; } @Override public CAstNode getAST() { return Ast; } @Override public CAstType getType() { return type; } @Override public CAstControlFlowRecorder getControlFlow() { return cfg; } @Override public CAstSourcePositionRecorder getSourceMap() { return src; } @Override public CAstNodeTypeMapRecorder getNodeTypeMap() { return types; } public void setGotoTarget(CAstNode from, CAstNode to) { setLabelledGotoTarget(from, to, null); } public void setLabelledGotoTarget(CAstNode from, CAstNode to, Object label) { if (!cfg.isMapped(from)) { cfg.map(from, from); } if (!cfg.isMapped(to)) { cfg.map(to, to); } cfg.add(from, to, label); } public void setNodePosition(CAstNode n, Position pos) { src.setPosition(n, pos); } public void setNodeType(CAstNode n, CAstType type) { types.add(n, type); } public void setAst(CAstNode Ast) { this.Ast = Ast; } }
2,163
23.873563
84
java
WALA
WALA-master/cast/src/main/java/com/ibm/wala/cast/ir/translator/AbstractDataEntity.java
/* * Copyright (c) 2002 - 2014 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.cast.ir.translator; import com.ibm.wala.cast.tree.CAstControlFlowMap; import com.ibm.wala.cast.tree.CAstNode; import com.ibm.wala.cast.tree.CAstNodeTypeMap; import com.ibm.wala.cast.tree.CAstSourcePositionMap; abstract class AbstractDataEntity extends AbstractEntity { @Override public CAstNode getAST() { return null; } @Override public CAstControlFlowMap getControlFlow() { return null; } @Override public CAstSourcePositionMap getSourceMap() { return null; } @Override public CAstNodeTypeMap getNodeTypeMap() { return null; } @Override public String[] getArgumentNames() { return new String[0]; } @Override public CAstNode[] getArgumentDefaults() { return new CAstNode[0]; } @Override public int getArgumentCount() { return 0; } }
1,209
21
72
java
WALA
WALA-master/cast/src/main/java/com/ibm/wala/cast/ir/translator/AbstractEntity.java
/* * Copyright (c) 2002 - 2014 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.cast.ir.translator; import com.ibm.wala.cast.tree.CAstAnnotation; import com.ibm.wala.cast.tree.CAstEntity; import com.ibm.wala.cast.tree.CAstNode; import com.ibm.wala.cast.tree.CAstSourcePositionMap.Position; import com.ibm.wala.util.collections.EmptyIterator; import com.ibm.wala.util.collections.HashMapFactory; import com.ibm.wala.util.collections.HashSetFactory; import com.ibm.wala.util.debug.Assertions; import java.util.Collection; import java.util.Iterator; import java.util.Map; public abstract class AbstractEntity implements CAstEntity { private Position sourcePosition; private final Map<CAstNode, Collection<CAstEntity>> scopedEntities = HashMapFactory.make(); @Override public Map<CAstNode, Collection<CAstEntity>> getAllScopedEntities() { return scopedEntities; } @Override public String getSignature() { Assertions.UNREACHABLE(); return null; } @Override public Collection<CAstAnnotation> getAnnotations() { return null; } public void setPosition(Position pos) { sourcePosition = pos; } @Override public Position getPosition() { return sourcePosition; } @Override public Iterator<CAstEntity> getScopedEntities(CAstNode construct) { if (scopedEntities.containsKey(construct)) { return scopedEntities.get(construct).iterator(); } else { return EmptyIterator.instance(); } } public void addScopedEntity(CAstNode construct, CAstEntity child) { if (!scopedEntities.containsKey(construct)) { Collection<CAstEntity> set = HashSetFactory.make(1); scopedEntities.put(construct, set); } scopedEntities.get(construct).add(child); } }
2,061
27.246575
93
java
WALA
WALA-master/cast/src/main/java/com/ibm/wala/cast/ir/translator/AbstractFieldEntity.java
/* * Copyright (c) 2002 - 2014 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.cast.ir.translator; import com.ibm.wala.cast.tree.CAstEntity; import com.ibm.wala.cast.tree.CAstQualifier; import com.ibm.wala.cast.tree.CAstType; import com.ibm.wala.util.debug.Assertions; import java.util.Collection; import java.util.HashSet; import java.util.Set; public abstract class AbstractFieldEntity extends AbstractDataEntity { private final String name; private final Set<CAstQualifier> modifiers; private final CAstEntity declaringClass; public AbstractFieldEntity( String name, Set<CAstQualifier> modifiers, boolean isStatic, CAstEntity declaringClass) { this.name = name; this.declaringClass = declaringClass; this.modifiers = new HashSet<>(); if (modifiers != null) { this.modifiers.addAll(modifiers); } if (isStatic) { this.modifiers.add(CAstQualifier.STATIC); } } @Override public String toString() { return "field " + name + " of " + declaringClass.getName(); } @Override public int getKind() { return FIELD_ENTITY; } @Override public String getName() { return name; } @Override public CAstType getType() { Assertions.UNREACHABLE(); return null; } @Override public Collection<CAstQualifier> getQualifiers() { return modifiers; } }
1,667
23.173913
95
java
WALA
WALA-master/cast/src/main/java/com/ibm/wala/cast/ir/translator/AbstractGlobalEntity.java
/* * Copyright (c) 2002 - 2014 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.cast.ir.translator; import com.ibm.wala.cast.tree.CAstQualifier; import com.ibm.wala.cast.tree.CAstType; import java.util.Collection; import java.util.HashSet; import java.util.Set; public abstract class AbstractGlobalEntity extends AbstractDataEntity { private final String name; private final Set<CAstQualifier> modifiers; private final CAstType type; public AbstractGlobalEntity(String name, CAstType type, Set<CAstQualifier> modifiers) { this.name = name; this.type = type; this.modifiers = new HashSet<>(); if (modifiers != null) { this.modifiers.addAll(modifiers); } } @Override public String toString() { if (type == null) { return "global " + name; } else { return "global " + name + ':' + type; } } @Override public int getKind() { return GLOBAL_ENTITY; } @Override public String getName() { return name; } @Override public CAstType getType() { return type; } @Override public Collection<CAstQualifier> getQualifiers() { return modifiers; } }
1,465
21.553846
89
java
WALA
WALA-master/cast/src/main/java/com/ibm/wala/cast/ir/translator/AbstractScriptEntity.java
/* * Copyright (c) 2002 - 2014 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.cast.ir.translator; import com.ibm.wala.cast.tree.CAstNode; import com.ibm.wala.cast.tree.CAstQualifier; import com.ibm.wala.cast.tree.CAstType; import java.io.File; import java.util.Collection; import java.util.Collections; public abstract class AbstractScriptEntity extends AbstractCodeEntity { private final File file; public AbstractScriptEntity(File file, CAstType type) { super(type); this.file = file; } public AbstractScriptEntity(String file, CAstType type) { this(new File(file), type); } @Override public int getKind() { return SCRIPT_ENTITY; } protected File getFile() { return file; } @Override public String getName() { return "script " + (file.isAbsolute() || file.getPath().startsWith("file:") ? file.getName() : file.getPath()); } @Override public String toString() { return "script " + file.getName(); } @Override public String[] getArgumentNames() { return new String[] {"script object"}; } @Override public CAstNode[] getArgumentDefaults() { return new CAstNode[0]; } @Override public int getArgumentCount() { return 1; } @Override public Collection<CAstQualifier> getQualifiers() { return Collections.emptySet(); } public String getFileName() { return file.getAbsolutePath(); } }
1,751
21.177215
72
java
WALA
WALA-master/cast/src/main/java/com/ibm/wala/cast/ir/translator/ArrayOpHandler.java
/* * Copyright (c) 2013 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.cast.ir.translator; import com.ibm.wala.cast.ir.translator.AstTranslator.WalkContext; import com.ibm.wala.cast.tree.CAstNode; public interface ArrayOpHandler { void doArrayRead( WalkContext context, int result, int arrayValue, CAstNode arrayRef, int[] dimValues); void doArrayWrite( WalkContext context, int arrayValue, CAstNode arrayRef, int[] dimValues, int rval); }
777
32.826087
91
java
WALA
WALA-master/cast/src/main/java/com/ibm/wala/cast/ir/translator/AstTranslator.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.cast.ir.translator; import com.ibm.wala.cast.ir.ssa.AssignInstruction; import com.ibm.wala.cast.ir.ssa.AstAssertInstruction; import com.ibm.wala.cast.ir.ssa.AstEchoInstruction; import com.ibm.wala.cast.ir.ssa.AstGlobalRead; import com.ibm.wala.cast.ir.ssa.AstGlobalWrite; import com.ibm.wala.cast.ir.ssa.AstInstructionFactory; import com.ibm.wala.cast.ir.ssa.AstIsDefinedInstruction; import com.ibm.wala.cast.ir.ssa.AstLexicalAccess.Access; import com.ibm.wala.cast.ir.ssa.AstLexicalRead; import com.ibm.wala.cast.ir.ssa.AstLexicalWrite; import com.ibm.wala.cast.ir.ssa.AstYieldInstruction; import com.ibm.wala.cast.ir.ssa.CAstBinaryOp; import com.ibm.wala.cast.ir.ssa.CAstUnaryOp; import com.ibm.wala.cast.ir.ssa.EachElementGetInstruction; import com.ibm.wala.cast.ir.ssa.EachElementHasNextInstruction; import com.ibm.wala.cast.ir.ssa.SSAConversion; import com.ibm.wala.cast.loader.AstMethod; import com.ibm.wala.cast.loader.AstMethod.DebuggingInformation; import com.ibm.wala.cast.loader.AstMethod.LexicalInformation; import com.ibm.wala.cast.loader.CAstAbstractLoader; import com.ibm.wala.cast.tree.CAstControlFlowMap; import com.ibm.wala.cast.tree.CAstEntity; import com.ibm.wala.cast.tree.CAstNode; import com.ibm.wala.cast.tree.CAstSourcePositionMap; import com.ibm.wala.cast.tree.CAstSourcePositionMap.Position; import com.ibm.wala.cast.tree.CAstSymbol; import com.ibm.wala.cast.tree.CAstType; import com.ibm.wala.cast.tree.impl.AbstractSourcePosition; import com.ibm.wala.cast.tree.impl.CAstImpl; import com.ibm.wala.cast.tree.impl.CAstOperator; import com.ibm.wala.cast.tree.impl.CAstSymbolImpl; import com.ibm.wala.cast.tree.impl.CAstSymbolImplBase; import com.ibm.wala.cast.tree.rewrite.CAstCloner; import com.ibm.wala.cast.tree.rewrite.CAstRewriter; import com.ibm.wala.cast.tree.visit.CAstVisitor; import com.ibm.wala.cast.types.AstTypeReference; import com.ibm.wala.cast.util.CAstPrinter; import com.ibm.wala.cast.util.SourceBuffer; import com.ibm.wala.cfg.AbstractCFG; import com.ibm.wala.cfg.IBasicBlock; import com.ibm.wala.classLoader.CallSiteReference; import com.ibm.wala.classLoader.IClassLoader; import com.ibm.wala.classLoader.IMethod; import com.ibm.wala.classLoader.ModuleEntry; import com.ibm.wala.core.util.strings.Atom; import com.ibm.wala.core.util.warnings.Warning; import com.ibm.wala.ipa.callgraph.CGNode; import com.ibm.wala.shrike.shrikeBT.BinaryOpInstruction; import com.ibm.wala.shrike.shrikeBT.ConditionalBranchInstruction; import com.ibm.wala.shrike.shrikeBT.IBinaryOpInstruction; import com.ibm.wala.shrike.shrikeBT.IConditionalBranchInstruction; import com.ibm.wala.shrike.shrikeBT.IUnaryOpInstruction; import com.ibm.wala.shrike.shrikeBT.ShiftInstruction; import com.ibm.wala.ssa.SSAAbstractInvokeInstruction; import com.ibm.wala.ssa.SSAConditionalBranchInstruction; import com.ibm.wala.ssa.SSAGetCaughtExceptionInstruction; import com.ibm.wala.ssa.SSAGotoInstruction; import com.ibm.wala.ssa.SSAInstruction; import com.ibm.wala.ssa.SSAInstructionFactory; import com.ibm.wala.ssa.SSAMonitorInstruction; import com.ibm.wala.ssa.SSAThrowInstruction; import com.ibm.wala.ssa.SymbolTable; import com.ibm.wala.types.FieldReference; import com.ibm.wala.types.TypeName; import com.ibm.wala.types.TypeReference; import com.ibm.wala.util.collections.HashMapFactory; import com.ibm.wala.util.collections.HashSetFactory; import com.ibm.wala.util.collections.Iterator2Iterable; import com.ibm.wala.util.collections.MapUtil; import com.ibm.wala.util.collections.Pair; import com.ibm.wala.util.debug.Assertions; import com.ibm.wala.util.debug.UnimplementedError; import com.ibm.wala.util.graph.impl.SparseNumberedGraph; import com.ibm.wala.util.graph.traverse.DFS; import com.ibm.wala.util.intset.IntSet; import com.ibm.wala.util.intset.IntSetUtil; import com.ibm.wala.util.intset.MutableIntSet; import java.io.IOException; import java.io.Reader; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.NavigableSet; import java.util.Set; import java.util.SortedSet; import java.util.function.Function; /** * Common code to translate CAst to IR. Must be specialized by each language to handle semantics * appropriately. */ public abstract class AstTranslator extends CAstVisitor<AstTranslator.WalkContext> implements ArrayOpHandler, TranslatorToIR { /** * does the language care about using type-appropriate default values? For Java, the answer is yes * (ints should get a default value of 0, null for pointers, etc.). For JavaScript, the answer is * no, as any variable can hold the value 'undefined'. */ protected abstract boolean useDefaultInitValues(); /** can lexical reads / writes access globals? */ protected abstract boolean treatGlobalsAsLexicallyScoped(); protected boolean topLevelFunctionsInGlobalScope() { return true; } /** * for a block that catches all exceptions, what is the root exception type that it can catch? * E.g., for Java, java.lang.Throwable */ protected abstract TypeReference defaultCatchType(); protected abstract TypeReference makeType(CAstType type); /** * define a new (presumably nested) type. return true if type was successfully defined, false * otherwise */ protected abstract boolean defineType(CAstEntity type, WalkContext wc); /** declare a new function, represented by N */ protected abstract void declareFunction(CAstEntity N, WalkContext context); /** fully define a function. invoked after all the code of the function has been processed */ protected abstract void defineFunction( CAstEntity N, WalkContext definingContext, AbstractCFG<SSAInstruction, ? extends IBasicBlock<SSAInstruction>> cfg, SymbolTable symtab, boolean hasCatchBlock, Map<IBasicBlock<SSAInstruction>, TypeReference[]> catchTypes, boolean hasMonitorOp, AstLexicalInformation lexicalInfo, DebuggingInformation debugInfo); /** define a new field fieldEntity within topEntity */ protected abstract void defineField( CAstEntity topEntity, WalkContext context, CAstEntity fieldEntity); /** create the language-appropriate name for f */ protected abstract String composeEntityName(WalkContext parent, CAstEntity f); /** generate IR for a CAst throw expression, updating context.cfg() */ protected abstract void doThrow(WalkContext context, int exception); /** generate IR for a CAst array read, updating context.cfg() */ @Override public abstract void doArrayRead( WalkContext context, int result, int arrayValue, CAstNode arrayRef, int[] dimValues); /** generate IR for a CAst array write, updating context.cfg() */ @Override public abstract void doArrayWrite( WalkContext context, int arrayValue, CAstNode arrayRef, int[] dimValues, int rval); /** generate IR for a CAst field read, updating context.cfg() */ protected abstract void doFieldRead( WalkContext context, int result, int receiver, CAstNode elt, CAstNode parent); /** generate IR for a CAst field write, updating context.cfg() */ protected abstract void doFieldWrite( WalkContext context, int receiver, CAstNode elt, CAstNode parent, int rval); /** generate IR for a CAst function expression, updating context.cfg() */ protected abstract void doMaterializeFunction( CAstNode node, WalkContext context, int result, int exception, CAstEntity fn); /** generate IR for a CAst new expression, updating context.cfg() */ protected abstract void doNewObject( WalkContext context, CAstNode newNode, int result, Object type, int[] arguments); /** generate IR for a CAst method call expression, updating context.cfg() */ protected abstract void doCall( WalkContext context, CAstNode call, int result, int exception, CAstNode name, int receiver, int[] arguments); /** the most-general type for the language being translated */ protected abstract CAstType topType(); /** the most-general exception type for the language being translated */ protected abstract CAstType exceptionType(); /** lift variable declarations for lexical scoping purposes? */ protected boolean liftDeclarationsForLexicalScoping() { return false; } /** used to generate instructions for array operations; defaults to this */ private final ArrayOpHandler arrayOpHandler; protected boolean isExceptionLabel(Object label) { if (label == null) return false; if (label instanceof Boolean) return false; if (label instanceof Number) return false; if (label == CAstControlFlowMap.SWITCH_DEFAULT) return false; return true; } /** * If this returns true, new global declarations get created for any attempt to access a * non-existent variable (believe it or not, JavaScript actually does this!) */ protected boolean hasImplicitGlobals() { return false; } /** * If this returns true, then attempts to lookup non-existent names return `null' rather than * tripping an assertion. This can be used when special handling is needed for built-in names. * (PHP does this) */ protected boolean hasSpecialUndeclaredVariables() { return false; } /** * some languages let you omit initialization of certain fields when writing an object literal * (e.g., PHP). This method should be overridden to handle such cases. */ protected void handleUnspecifiedLiteralKey() { Assertions.UNREACHABLE(); } /** generate prologue code for each function body */ protected void doPrologue(WalkContext context) { // perform a lexical write to copy the value stored in the local // associated with each parameter to the lexical name final CAstEntity entity = context.top(); Set<String> exposedNames = entity2ExposedNames.get(entity); if (exposedNames != null) { int i = 0; for (String arg : entity.getArgumentNames()) { if (exposedNames.contains(arg)) { final Scope currentScope = context.currentScope(); Symbol symbol = currentScope.lookup(arg); assert symbol.getDefiningScope() == currentScope; int argVN = symbol.valueNumber(); CAstType type = (entity.getType() instanceof CAstType.Method) ? (CAstType) ((CAstType.Method) entity.getType()).getArgumentTypes().get(i) : topType(); Access A = new Access(arg, context.getEntityName(entity), makeType(type), argVN); context.cfg().addInstruction(new AstLexicalWrite(context.cfg().currentInstruction, A)); addExposedName(entity, entity, arg, argVN, true, context); } } } } /** generate IR for call modeling creation of primitive value, updating context.cfg() */ protected abstract void doPrimitive(int resultVal, WalkContext context, CAstNode primitiveCall); /** * get the value number for a name defined locally (i.e., within the current method) by looking up * the name in context.currentScope(). Note that the caller is responsible for ensuring that name * is defined in the local scope. */ protected int doLocalRead(WalkContext context, String name, TypeReference type) { CAstEntity entity = context.top(); Set<String> exposed = entity2ExposedNames.get(entity); if (exposed != null && exposed.contains(name)) { return doLexReadHelper(context, name, type); } return context.currentScope().lookup(name).valueNumber(); } /** * add an {@link AssignInstruction} to context.cfg() that copies rval to the value number of local * nm. Note that the caller is responsible for ensuring that nm is defined in the local scope. */ protected void doLocalWrite(WalkContext context, String nm, TypeReference type, int rval) { CAstEntity entity = context.top(); Set<String> exposed = entity2ExposedNames.get(entity); if (exposed != null && exposed.contains(nm)) { // use a lexical write doLexicallyScopedWrite(context, nm, type, rval); // return; } int lval = context.currentScope().lookup(nm).valueNumber(); if (lval != rval) { context .cfg() .addInstruction(new AssignInstruction(context.cfg().currentInstruction, lval, rval)); } } /** * Note that the caller is responsible for ensuring that name is defined in a lexical scope. * * @param node the AST node representing the read */ protected int doLexicallyScopedRead( CAstNode node, WalkContext context, final String name, TypeReference type) { return doLexReadHelper(context, name, type); } /** * @param name A variable name * @return is this name safe to overwrite, i.e. it's synthetic from the translator? */ protected boolean ignoreName(String name) { return false; } /** * we only have this method to avoid having to pass a node parameter at other call sites, as would * be required for {@link #doLexicallyScopedRead(CAstNode, WalkContext, String, TypeReference)} */ private int doLexReadHelper(WalkContext context, final String name, TypeReference type) { Symbol S = context.currentScope().lookup(name); Scope definingScope = S.getDefiningScope(); CAstEntity E = definingScope.getEntity(); if (E.equals(context.currentScope().getEntity()) && !(entity2WrittenNames.containsKey(E) && entity2WrittenNames.get(E).stream() .filter(p -> p.snd.equals(name) && p.fst != E) .iterator() .hasNext())) { return definingScope.lookup(name).valueNumber(); } else { // record in declaring scope that the name is exposed to a nested scope addExposedName(E, E, name, definingScope.lookup(name).valueNumber(), false, context); final String entityName = context.getEntityName(E); int result = context.currentScope().allocateTempValue(); Access A = new Access(name, entityName, type, result); context.cfg().addInstruction(new AstLexicalRead(context.cfg().currentInstruction, A)); markExposedInEnclosingEntities(context, name, definingScope, type, E, entityName, false); return result; } } /** * record name as exposed for the current entity and for all enclosing entities up to that of the * defining scope, since if the name is updated via a call to a nested function, SSA for these * entities may need to be updated with the new definition */ private static void markExposedInEnclosingEntities( WalkContext context, final String name, Scope definingScope, TypeReference type, CAstEntity E, final String entityName, boolean isWrite) { Scope curScope = context.currentScope(); while (!curScope.equals(definingScope)) { final Symbol curSymbol = curScope.lookup(name); final int vn = curSymbol.valueNumber(); final Access A = new Access(name, entityName, type, vn); final CAstEntity entity = curScope.getEntity(); if (entity != definingScope.getEntity()) { addExposedName(entity, E, name, vn, isWrite, context); // record the access; later, the Accesses in the instruction // defining vn will be adjusted based on this information; see // patchLexicalAccesses() addAccess(context, entity, A); } curScope = curScope.getParent(); } } /** Note that the caller is responsible for ensuring that name is defined in a lexical scope. */ protected void doLexicallyScopedWrite( WalkContext context, String name, TypeReference type, int rval) { Symbol S = context.currentScope().lookup(name); Scope definingScope = S.getDefiningScope(); CAstEntity E = definingScope.getEntity(); // record in declaring scope that the name is exposed to a nested scope addExposedName(E, E, name, definingScope.lookup(name).valueNumber(), true, context); // lexically-scoped variables must be written in their scope each time Access A = new Access(name, context.getEntityName(E), type, rval); context.cfg().addInstruction(new AstLexicalWrite(context.cfg().currentInstruction, A)); markExposedInEnclosingEntities( context, name, definingScope, type, E, context.getEntityName(E), true); int lval = S.valueNumber(); if (lval != rval) { context .cfg() .addInstruction(new AssignInstruction(context.cfg().currentInstruction, lval, rval)); } } /** generate instructions for a read of a global */ protected int doGlobalRead( @SuppressWarnings("unused") CAstNode node, WalkContext context, String name, TypeReference type) { // Global variables can be treated as lexicals defined in the CG root, or if (treatGlobalsAsLexicallyScoped()) { int result = context.currentScope().allocateTempValue(); Access A = new Access(name, null, type, result); context.cfg().addInstruction(new AstLexicalRead(context.cfg().currentInstruction, A)); addAccess(context, context.top(), A); return result; // globals can be treated as a single static location } else { int result = context.currentScope().allocateTempValue(); FieldReference global = makeGlobalRef(name); context .cfg() .addInstruction(new AstGlobalRead(context.cfg().currentInstruction, result, global)); return result; } } /** generate instructions for a write of a global */ protected void doGlobalWrite(WalkContext context, String name, TypeReference type, int rval) { // Global variables can be treated as lexicals defined in the CG root, or if (treatGlobalsAsLexicallyScoped()) { Access A = new Access(name, null, type, rval); context.cfg().addInstruction(new AstLexicalWrite(context.cfg().currentInstruction, A)); addAccess(context, context.top(), A); // globals can be treated as a single static location } else { FieldReference global = makeGlobalRef(name); context .cfg() .addInstruction(new AstGlobalWrite(context.cfg().currentInstruction, global, rval)); } } /** * creates a reference to a global named globalName. the declaring type and type of the global are * both the root type. */ protected FieldReference makeGlobalRef(String globalName) { TypeReference rootTypeRef = TypeReference.findOrCreate(loader.getReference(), AstTypeReference.rootTypeName); return FieldReference.findOrCreate( rootTypeRef, Atom.findOrCreateUnicodeAtom("global " + globalName), rootTypeRef); } protected final IClassLoader loader; /** * for handling languages that let you include other source files named statically (e.g., ABAP) */ protected final Map<Object, CAstEntity> namedEntityResolver; protected final SSAInstructionFactory insts; protected AstTranslator( IClassLoader loader, Map<Object, CAstEntity> namedEntityResolver, ArrayOpHandler arrayOpHandler) { this.loader = loader; this.namedEntityResolver = namedEntityResolver; this.arrayOpHandler = arrayOpHandler != null ? arrayOpHandler : this; this.insts = loader.getInstructionFactory(); } protected AstTranslator(IClassLoader loader, Map<Object, CAstEntity> namedEntityResolver) { this(loader, namedEntityResolver, null); } protected AstTranslator(IClassLoader loader) { this(loader, null); } /** for keeping position information for the generated SSAInstructions and SSA locals */ private static class AstDebuggingInformation implements DebuggingInformation { private final Position codeBodyPosition; private final Position codeBodyNamePosition; private final String[][] valueNumberNames; private final Position[] instructionPositions; private final Position[][] operandPositions; private final Position[] parameterPositions; private final NavigableSet<Position> codePositions; AstDebuggingInformation( Position codeBodyNamePosition, Position codeBodyPosition, Position[] instructionPositions, Position[][] operandPositions, Position[] parameterPositions, String[] names, NavigableSet<Position> codePositions) { this.codePositions = codePositions; this.codeBodyNamePosition = codeBodyNamePosition; this.codeBodyPosition = codeBodyPosition; this.instructionPositions = instructionPositions; this.operandPositions = operandPositions; this.parameterPositions = parameterPositions; valueNumberNames = new String[names.length][]; for (int i = 0; i < names.length; i++) { if (names[i] != null) { valueNumberNames[i] = new String[] {names[i]}; } else { valueNumberNames[i] = new String[0]; } } } @Override public Position getCodeBodyPosition() { return codeBodyPosition; } @Override public Position getCodeNamePosition() { return codeBodyNamePosition; } @Override public Position getInstructionPosition(int instructionOffset) { return instructionPositions[instructionOffset]; } @Override public Position getOperandPosition(int instructionOffset, int operand) { if (operandPositions[instructionOffset] != null && operandPositions[instructionOffset].length > operand) { return operandPositions[instructionOffset][operand]; } else { return null; } } @Override public String[][] getSourceNamesForValues() { return valueNumberNames; } @Override public Position getParameterPosition(int param) { return parameterPositions[param]; } private static boolean disjoint(Position a, Position b) { return (a.getLastLine() < b.getFirstLine() || (a.getLastLine() == b.getFirstLine() && a.getLastCol() < b.getFirstCol())) || (b.getLastLine() < a.getFirstLine() || (b.getLastLine() == a.getFirstLine() && b.getLastCol() < a.getFirstCol())); } private String getComment(int instructionOffset, Function<Position, SortedSet<Position>> set) throws IOException { Position pos = getInstructionPosition(instructionOffset); if (pos == null) { return null; } else { SortedSet<Position> prevSet = set.apply(pos); if (prevSet != null && !prevSet.isEmpty()) { Position ppos = null; for (Position other : prevSet) { if (disjoint(other, pos)) { ppos = other; break; } } if (ppos == null) { return null; } Position first, second; if (ppos.compareTo(pos) < 0) { first = ppos; second = pos; } else { first = pos; second = ppos; } Position intermediate = new AbstractSourcePosition() { @Override public URL getURL() { return pos.getURL(); } @Override public Reader getReader() throws IOException { return pos.getReader(); } @Override public int getFirstLine() { return first.getLastLine(); } @Override public int getLastLine() { return second.getFirstLine(); } @Override public int getFirstCol() { return first.getLastCol(); } @Override public int getLastCol() { return second.getFirstCol(); } @Override public int getFirstOffset() { return first.getLastOffset(); } @Override public int getLastOffset() { return second.getFirstOffset(); } }; return new SourceBuffer(intermediate).toString(); } } return null; } @Override public String getFollowingComment(int instructionOffset) throws IOException { return getComment(instructionOffset, codePositions::tailSet); } @Override public String getLeadingComment(int instructionOffset) throws IOException { return getComment(instructionOffset, codePositions::headSet); } } public static final boolean DEBUG_ALL = false; public static final boolean DEBUG_TOP = DEBUG_ALL || false; public static final boolean DEBUG_CFG = DEBUG_ALL || false; public static final boolean DEBUG_NAMES = DEBUG_ALL || false; public static final boolean DEBUG_LEXICAL = DEBUG_ALL || false; /** * basic block implementation used in the CFGs constructed during the IR-generating AST traversal */ protected static final class PreBasicBlock implements IBasicBlock<SSAInstruction> { private static final int NORMAL = 0; private static final int HANDLER = 1; private static final int ENTRY = 2; private static final int EXIT = 3; private int kind = NORMAL; private int number = -1; private int firstIndex = -1; private int lastIndex = -2; private final List<SSAInstruction> instructions = new ArrayList<>(); @Override public int getNumber() { return getGraphNodeId(); } @Override public int getGraphNodeId() { return number; } @Override public void setGraphNodeId(int number) { this.number = number; } @Override public int getFirstInstructionIndex() { return firstIndex; } void setFirstIndex(int firstIndex) { this.firstIndex = firstIndex; } @Override public int getLastInstructionIndex() { return lastIndex; } void setLastIndex(int lastIndex) { this.lastIndex = lastIndex; } void makeExitBlock() { kind = EXIT; } void makeEntryBlock() { kind = ENTRY; } void makeHandlerBlock() { kind = HANDLER; } @Override public boolean isEntryBlock() { return kind == ENTRY; } @Override public boolean isExitBlock() { return kind == EXIT; } public boolean isHandlerBlock() { return kind == HANDLER; } @Override public String toString() { return "PreBB" + number + ':' + firstIndex + ".." + lastIndex; } private List<SSAInstruction> instructions() { return instructions; } @Override public boolean isCatchBlock() { return (lastIndex > -1) && (instructions.get(0) instanceof SSAGetCaughtExceptionInstruction); } @Override public IMethod getMethod() { return null; } @Override public Iterator<SSAInstruction> iterator() { return instructions.iterator(); } } protected static final class UnwindState { final CAstNode unwindAst; final WalkContext astContext; final CAstVisitor<WalkContext> astVisitor; UnwindState(CAstNode unwindAst, WalkContext astContext, CAstVisitor<WalkContext> astVisitor) { this.unwindAst = unwindAst; this.astContext = astContext; this.astVisitor = astVisitor; } public UnwindState getParent() { return astContext.getUnwindState(); } @Override public int hashCode() { return astContext.hashCode() * unwindAst.hashCode() * astVisitor.hashCode(); } @Override public boolean equals(Object o) { if (o instanceof UnwindState) { if (((UnwindState) o).unwindAst != unwindAst) return false; if (((UnwindState) o).astVisitor != astVisitor) return false; if (getParent() == null) { return ((UnwindState) o).getParent() == null; } else { return getParent().equals(((UnwindState) o).getParent()); } } return false; } boolean covers(UnwindState other) { if (equals(other)) return true; if (getParent() != null) return getParent().covers(other); return false; } } /** * holds the control-flow graph as it is being constructed. When construction is complete, * information is stored in an {@link AstCFG} */ public final class IncipientCFG extends SparseNumberedGraph<PreBasicBlock> { protected class Unwind { private final Map<PreBasicBlock, UnwindState> unwindData = new LinkedHashMap<>(); /** a cache of generated blocks */ private final Map<Pair<UnwindState, Pair<PreBasicBlock, Boolean>>, PreBasicBlock> code = new LinkedHashMap<>(); void setUnwindState(PreBasicBlock block, UnwindState context) { unwindData.put(block, context); } void setUnwindState(CAstNode node, UnwindState context) { unwindData.put(nodeToBlock.get(node), context); } /** * When adding an edge from source to target, it is possible that certain exception-handling * code needs to be executed before the control is actually transfered to target. This method * determines if this is the case, and if so, it generates the exception handler blocks and * adds an appropriate edge to the target. It returns the basic block that should be the * target of the edge from source (target itself if there is no exception-handling code, the * initial catch block otherwise) */ public PreBasicBlock findOrCreateCode( PreBasicBlock source, PreBasicBlock target, final boolean exception) { UnwindState sourceContext = unwindData.get(source); final CAstNode dummy = exception ? new CAstImpl().makeNode(CAstNode.EMPTY) : null; // no unwinding is needed, so jump to target block directly if (sourceContext == null) return target; WalkContext astContext = sourceContext.astContext; UnwindState targetContext = null; if (target != null) targetContext = unwindData.get(target); // in unwind context, but catch in same (or inner) unwind context if (targetContext != null && targetContext.covers(sourceContext)) return target; Pair<UnwindState, Pair<PreBasicBlock, Boolean>> key = Pair.make(sourceContext, Pair.make(target, exception)); if (code.containsKey(key)) { return code.get(key); } else { int e = -1; PreBasicBlock currentBlock = getCurrentBlock(); if (!isDeadBlock(currentBlock)) { addInstruction(insts.GotoInstruction(currentInstruction, -1)); newBlock(false); } PreBasicBlock startBlock = getCurrentBlock(); if (exception) { setCurrentBlockAsHandler(); e = sourceContext.astContext.currentScope().allocateTempValue(); addInstruction( insts.GetCaughtExceptionInstruction(currentInstruction, startBlock.getNumber(), e)); sourceContext.astContext.setCatchType(startBlock, defaultCatchType()); } while (sourceContext != null && (targetContext == null || !targetContext.covers(sourceContext))) { final CAstRewriter.Rewrite ast = new CAstCloner(new CAstImpl()) { @Override protected CAstNode flowOutTo( Map<Pair<CAstNode, NoKey>, CAstNode> nodeMap, CAstNode oldSource, Object label, CAstNode oldTarget, CAstControlFlowMap orig, CAstSourcePositionMap src) { if (exception && !isExceptionLabel(label)) { return dummy; } else { return oldTarget; } } }.copy( sourceContext.unwindAst, sourceContext.astContext.getControlFlow(), sourceContext.astContext.getSourceMap(), sourceContext.astContext.top().getNodeTypeMap(), sourceContext.astContext.top().getAllScopedEntities(), sourceContext.astContext.top().getArgumentDefaults()); sourceContext.astVisitor.visit( ast.newRoot(), new DelegatingContext(sourceContext.astContext) { @Override public CAstSourcePositionMap getSourceMap() { return ast.newPos(); } @Override public CAstControlFlowMap getControlFlow() { return ast.newCfg(); } }, sourceContext.astVisitor); sourceContext = sourceContext.getParent(); } PreBasicBlock endBlock = getCurrentBlock(); if (exception) { assert unwindData.get(endBlock) == null; addPreNode(dummy); doThrow(astContext, e); } else { addInstruction(insts.GotoInstruction(currentInstruction, -1)); } newBlock(false); if (target != null) { addEdge(currentBlock, getCurrentBlock()); assert unwindData.get(getCurrentBlock()) == null; addEdge(endBlock, target); // assert unwindData.get(target) == null; // `null' target is idiom for branch/throw to exit } else { if (exception) { addEdge(currentBlock, getCurrentBlock()); } else { addDelayedEdge(endBlock, exitMarker, exception); } } code.put(key, startBlock); return startBlock; } } } private Unwind unwind = null; private final List<PreBasicBlock> blocks = new ArrayList<>(); private PreBasicBlock entryBlock; private final Map<CAstNode, PreBasicBlock> nodeToBlock = new LinkedHashMap<>(); private final Map<Object, Set<Pair<PreBasicBlock, Boolean>>> delayedEdges = new LinkedHashMap<>(); private final Object exitMarker = new Object(); private final Set<PreBasicBlock> deadBlocks = new LinkedHashSet<>(); private final Set<PreBasicBlock> normalToExit = new LinkedHashSet<>(); private final Set<PreBasicBlock> exceptionalToExit = new LinkedHashSet<>(); private Position[] linePositions = new Position[10]; private Position[][] operandPositions = new Position[10][]; private boolean hasCatchBlock = false; /** does the method have any monitor operations? */ private boolean hasMonitorOp = false; private int currentInstruction = 0; private PreBasicBlock currentBlock; public int getCurrentInstruction() { return currentInstruction; } public PreBasicBlock getCurrentBlock() { return currentBlock; } boolean hasCatchBlock() { return hasCatchBlock; } boolean hasMonitorOp() { return hasMonitorOp; } void noteCatchBlock() { hasCatchBlock = true; } Position[] getLinePositionMap() { return linePositions; } /** * create a new basic block, and set it as the current block. * * @param fallThruFromPrior should a fall-through edge be added from the previous block (value * of currentBlock at entry)? if false, the newly created block is marked as a dead block, * as it has no incoming edges. * @return the new block */ public PreBasicBlock newBlock(boolean fallThruFromPrior) { // optimization: if we have a fall-through from an empty block, just // return the empty block if (fallThruFromPrior && !currentBlock.isEntryBlock() && currentBlock.instructions().size() == 0) { return currentBlock; } PreBasicBlock previous = currentBlock; currentBlock = new PreBasicBlock(); addNode(currentBlock); blocks.add(currentBlock); if (DEBUG_CFG) System.err.println(("adding new block (node) " + currentBlock)); if (fallThruFromPrior) { if (DEBUG_CFG) System.err.println(("adding fall-thru edge " + previous + " --> " + currentBlock)); addEdge(previous, currentBlock); } else { deadBlocks.add(currentBlock); } return currentBlock; } /** * record a delayed edge addition from src to dst. Edge will be added when appropriate; see * {@link #checkForRealizedEdges(CAstNode)} and {@link * #checkForRealizedExitEdges(PreBasicBlock)} */ private void addDelayedEdge(PreBasicBlock src, Object dst, boolean exception) { MapUtil.findOrCreateSet(delayedEdges, dst).add(Pair.make(src, exception)); } void makeEntryBlock(PreBasicBlock bb) { entryBlock = bb; bb.makeEntryBlock(); } void makeExitBlock(PreBasicBlock bb) { bb.makeExitBlock(); for (PreBasicBlock p : Iterator2Iterable.make(getPredNodes(bb))) normalToExit.add(p); // now that we have created the exit block, add the delayed edges to the // exit checkForRealizedExitEdges(bb); } public void setCurrentBlockAsHandler() { currentBlock.makeHandlerBlock(); } boolean hasDelayedEdges(CAstNode n) { return delayedEdges.containsKey(n); } /** given some n which is now mapped by nodeToBlock, add any delayed edges to n's block */ private void checkForRealizedEdges(CAstNode n) { if (delayedEdges.containsKey(n)) { for (Pair<PreBasicBlock, Boolean> s : delayedEdges.get(n)) { PreBasicBlock src = s.fst; boolean exception = s.snd; if (unwind == null) { addEdge(src, nodeToBlock.get(n)); } else { PreBasicBlock target = nodeToBlock.get(n); addEdge(src, unwind.findOrCreateCode(src, target, exception)); } } delayedEdges.remove(n); } } /** add any delayed edges to the exit block */ private void checkForRealizedExitEdges(PreBasicBlock exitBlock) { if (delayedEdges.containsKey(exitMarker)) { for (Pair<PreBasicBlock, Boolean> s : delayedEdges.get(exitMarker)) { PreBasicBlock src = s.fst; boolean exception = s.snd; addEdge(src, exitBlock); if (exception) exceptionalToExit.add(src); else normalToExit.add(src); } delayedEdges.remove(exitMarker); } } private void setUnwindState(CAstNode node, UnwindState context) { if (unwind == null) unwind = new Unwind(); unwind.setUnwindState(node, context); } public void addPreNode(CAstNode n) { addPreNode(n, null); } /** associate n with the current block, and update the current unwind state */ public void addPreNode(CAstNode n, UnwindState context) { if (DEBUG_CFG) System.err.println(("adding pre-node " + n)); nodeToBlock.put(n, currentBlock); deadBlocks.remove(currentBlock); if (context != null) setUnwindState(n, context); // now that we've associated n with a block, add associated delayed edges checkForRealizedEdges(n); } public void addPreEdge(CAstNode src, CAstNode dst, boolean exception) { assert nodeToBlock.containsKey(src); addPreEdge(nodeToBlock.get(src), dst, exception); } /** * if dst is associated with a basic block b, add an edge from src to b. otherwise, record the * edge addition as delayed. */ public void addPreEdge(PreBasicBlock src, CAstNode dst, boolean exception) { if (dst == CAstControlFlowMap.EXCEPTION_TO_EXIT) { assert exception; addPreEdgeToExit(src, exception); } else if (nodeToBlock.containsKey(dst)) { PreBasicBlock target = nodeToBlock.get(dst); if (DEBUG_CFG) System.err.println(("adding pre-edge " + src + " --> " + dst)); if (unwind == null) { addEdge(src, target); } else { addEdge(src, unwind.findOrCreateCode(src, target, exception)); } } else { if (DEBUG_CFG) System.err.println(("adding delayed pre-edge " + src + " --> " + dst)); addDelayedEdge(src, dst, exception); } } public void addPreEdgeToExit(CAstNode src, boolean exception) { assert nodeToBlock.containsKey(src); addPreEdgeToExit(nodeToBlock.get(src), exception); } public void addPreEdgeToExit(PreBasicBlock src, boolean exception) { if (unwind != null) { PreBasicBlock handlers = unwind.findOrCreateCode(src, null, exception); if (handlers != null) { addEdge(src, handlers); return; } } addDelayedEdge(src, exitMarker, exception); } @Override public void addEdge(PreBasicBlock src, PreBasicBlock dst) { super.addEdge(src, dst); /* if (src.getLastInstructionIndex() >= 0) { SSAInstruction inst = src.instructions.get(src.instructions.size() - 1); if (inst instanceof SSAGotoInstruction) { Iterator<PreBasicBlock> blks = getSuccNodes(src); int succ = 0; while (blks.hasNext()) { if (!blks.next().isHandlerBlock()) { succ++; assert succ <= 1; } } } } */ deadBlocks.remove(dst); } public boolean isDeadBlock(PreBasicBlock block) { return deadBlocks.contains(block); } public PreBasicBlock getBlock(CAstNode n) { return nodeToBlock.get(n); } /** mark the current position as the position for the instruction */ private void noteLinePosition(int instruction) { ensurePositionSpace(instruction); linePositions[instruction] = getCurrentPosition(); } private void ensurePositionSpace(int instruction) { if (linePositions.length < (instruction + 1)) { linePositions = Arrays.copyOf(linePositions, instruction * 2 + 1); operandPositions = Arrays.copyOf(operandPositions, instruction * 2 + 1); } } public void noteOperands(int instruction, Position... operands) { ensurePositionSpace(instruction); operandPositions[instruction] = operands; } public void unknownInstructions(Runnable f) { Position save = currentPosition; currentPosition = CAstSourcePositionMap.NO_INFORMATION; f.run(); currentPosition = save; } public void addInstruction(SSAInstruction n) { deadBlocks.remove(currentBlock); int inst = currentInstruction++; noteLinePosition(inst); if (currentBlock.instructions().size() == 0) { currentBlock.setFirstIndex(inst); } else { for (SSAInstruction priorInst : currentBlock.instructions()) { assert !(priorInst instanceof SSAGotoInstruction); } assert !(n instanceof SSAGetCaughtExceptionInstruction); } if (DEBUG_CFG) { System.err.println(("adding " + n + " at " + inst + " to " + currentBlock)); } if (n instanceof SSAMonitorInstruction) { hasMonitorOp = true; } currentBlock.instructions().add(n); currentBlock.setLastIndex(inst); } @Override public String toString() { StringBuilder sb = new StringBuilder(super.toString()); for (PreBasicBlock b : blocks) { if (b.firstIndex > 0) { sb.append('\n').append(b); for (int i = 0; i < b.instructions.size(); i++) { sb.append('\n').append(b.instructions.get(i)); } } } return sb.toString(); } public Position[][] getOperandPositionMap() { return operandPositions; } } /** * data structure for the final CFG for a method, based on the information in an {@link * IncipientCFG} */ protected static final class AstCFG extends AbstractCFG<SSAInstruction, PreBasicBlock> { private SSAInstruction[] instructions; private final int[] instructionToBlockMap; private final int[] pcMap; private final String functionName; private final SymbolTable symtab; private interface EdgeOperation { void act(PreBasicBlock src, PreBasicBlock dst); } private void transferEdges( Set<PreBasicBlock> blocks, IncipientCFG icfg, EdgeOperation normal, EdgeOperation except) { for (PreBasicBlock src : blocks) { for (PreBasicBlock dst : Iterator2Iterable.make(icfg.getSuccNodes(src))) { if (isCatchBlock(dst.getNumber()) || (dst.isExitBlock() && icfg.exceptionalToExit.contains(src))) { except.act(src, dst); } if (dst.isExitBlock() ? icfg.normalToExit.contains(src) : !isCatchBlock(dst.getNumber())) { normal.act(src, dst); } } } } private static boolean checkBlockBoundaries(IncipientCFG icfg) { MutableIntSet boundaries = IntSetUtil.make(); for (PreBasicBlock b : icfg) { if (b.getFirstInstructionIndex() >= 0) { if (boundaries.contains(b.getFirstInstructionIndex())) { return false; } boundaries.add(b.getFirstInstructionIndex()); } if (b.getLastInstructionIndex() >= 0 && b.getLastInstructionIndex() != b.getFirstInstructionIndex()) { if (boundaries.contains(b.getLastInstructionIndex())) { return false; } boundaries.add(b.getLastInstructionIndex()); } } return true; } AstCFG(CAstEntity n, IncipientCFG icfg, SymbolTable symtab, SSAInstructionFactory insts) { super(null); Set<PreBasicBlock> liveBlocks = DFS.getReachableNodes(icfg, Collections.singleton(icfg.entryBlock)); List<PreBasicBlock> blocks = icfg.blocks; boolean hasDeadBlocks = blocks.size() > liveBlocks.size(); assert checkBlockBoundaries(icfg); this.symtab = symtab; functionName = n.getName(); instructionToBlockMap = new int[liveBlocks.size()]; pcMap = hasDeadBlocks ? new int[icfg.currentInstruction] : null; final Map<PreBasicBlock, Collection<PreBasicBlock>> normalEdges = hasDeadBlocks ? HashMapFactory.<PreBasicBlock, Collection<PreBasicBlock>>make() : null; final Map<PreBasicBlock, Collection<PreBasicBlock>> exceptionalEdges = hasDeadBlocks ? HashMapFactory.<PreBasicBlock, Collection<PreBasicBlock>>make() : null; if (hasDeadBlocks) { transferEdges( liveBlocks, icfg, (src, dst) -> { if (!normalEdges.containsKey(src)) { normalEdges.put(src, HashSetFactory.<PreBasicBlock>make()); } normalEdges.get(src).add(dst); }, (src, dst) -> { if (!exceptionalEdges.containsKey(src)) { exceptionalEdges.put(src, HashSetFactory.<PreBasicBlock>make()); } exceptionalEdges.get(src).add(dst); }); } int instruction = 0; for (int i = 0, blockNumber = 0; i < blocks.size(); i++) { PreBasicBlock block = blocks.get(i); block.setGraphNodeId(-1); if (liveBlocks.contains(block)) { if (hasDeadBlocks) { int offset = 0; for (int oldPC = block.getFirstInstructionIndex(); offset < block.instructions().size(); oldPC++, offset++) { pcMap[instruction + offset] = oldPC; } } if (block.getFirstInstructionIndex() >= 0) { block.setFirstIndex(instruction); block.setLastIndex((instruction += block.instructions().size()) - 1); } instructionToBlockMap[blockNumber] = block.getLastInstructionIndex(); this.addNode(block); if (block.isCatchBlock()) { setCatchBlock(blockNumber); } if (DEBUG_CFG) { System.err.println( ("added " + blocks.get(i) + " to final CFG as " + getNumber(blocks.get(i)))); } blockNumber++; } } init(); if (DEBUG_CFG) System.err.println((getMaxNumber() + " blocks total")); if (hasDeadBlocks) { for (PreBasicBlock src : blocks) { if (liveBlocks.contains(src)) { if (normalEdges.containsKey(src)) { for (PreBasicBlock succ : normalEdges.get(src)) { if (liveBlocks.contains(succ)) { addNormalEdge(src, succ); } } } if (exceptionalEdges.containsKey(src)) { for (PreBasicBlock succ : exceptionalEdges.get(src)) { if (liveBlocks.contains(succ)) { addExceptionalEdge(src, succ); } } } } } } else { transferEdges(liveBlocks, icfg, this::addNormalEdge, this::addExceptionalEdge); } int x = 0; instructions = new SSAInstruction[icfg.currentInstruction]; for (PreBasicBlock block : blocks) { if (liveBlocks.contains(block)) { List<SSAInstruction> bi = block.instructions(); for (SSAInstruction inst : bi) { if (inst instanceof SSAGetCaughtExceptionInstruction) { SSAGetCaughtExceptionInstruction ci = (SSAGetCaughtExceptionInstruction) inst; if (ci.getBasicBlockNumber() != block.getNumber()) { inst = insts.GetCaughtExceptionInstruction(x, block.getNumber(), ci.getException()); } } else if (inst instanceof SSAGotoInstruction) { Iterator<PreBasicBlock> succs = this.getNormalSuccessors(block).iterator(); if (succs.hasNext()) { PreBasicBlock target = succs.next(); assert liveBlocks.contains(target); assert !succs.hasNext() || !liveBlocks.contains(succs.next()) : "unexpected successors for block " + block + ": " + this; inst = insts.GotoInstruction(x, target.firstIndex); } else { // goto to the end of the method, so the instruction is unnecessary inst = null; } } else if (inst instanceof SSAThrowInstruction) { if (getExceptionalSuccessors(block).isEmpty()) { addExceptionalEdge(block, exit()); } } else if (inst instanceof SSAConditionalBranchInstruction) { Iterator<PreBasicBlock> succs = this.getNormalSuccessors(block).iterator(); assert succs.hasNext(); int target; int t1 = succs.next().firstIndex; if (succs.hasNext()) { int t2 = succs.next().firstIndex; if (t1 == x + 1) { target = t2; } else { target = t1; } } else { target = t1; } SSAConditionalBranchInstruction branch = (SSAConditionalBranchInstruction) inst; inst = insts.ConditionalBranchInstruction( x, branch.getOperator(), branch.getType(), branch.getUse(0), branch.getUse(1), target); } instructions[x++] = inst; } } } if (hasDeadBlocks) { for (int i = 0; i < instructions.length; i++) { if (instructions[i] != null) { if (instructions[i].iIndex() != i) { instructions[i].setInstructionIndex(i); } } } } if (instructions.length > x) { SSAInstruction[] ni = new SSAInstruction[x]; System.arraycopy(instructions, 0, ni, 0, x); instructions = ni; } } @Override public int hashCode() { return functionName.hashCode(); } @Override public boolean equals(Object o) { return (o instanceof AstCFG) && functionName.equals(((AstCFG) o).functionName); } @Override public PreBasicBlock getBlockForInstruction(int index) { for (int i = 1; i < getNumberOfNodes() - 1; i++) if (index <= instructionToBlockMap[i]) return getNode(i); return null; } @Override public SSAInstruction[] getInstructions() { return instructions; } @Override public int getProgramCounter(int index) { return pcMap == null ? index : pcMap[index]; } @Override public String toString() { SSAInstruction[] insts = getInstructions(); StringBuilder s = new StringBuilder("CAst CFG of " + functionName); int params[] = symtab.getParameterValueNumbers(); for (int param : params) s.append(' ').append(param); s.append('\n'); for (int i = 0; i < getNumberOfNodes(); i++) { PreBasicBlock bb = getNode(i); s.append(bb).append('\n'); for (PreBasicBlock pbb : Iterator2Iterable.make(getSuccNodes(bb))) s.append(" -->").append(pbb).append('\n'); for (int j = bb.getFirstInstructionIndex(); j <= bb.getLastInstructionIndex(); j++) if (insts[j] != null) s.append(" ").append(insts[j].toString(symtab)).append('\n'); } s.append("-- END --"); return s.toString(); } } public enum ScopeType { LOCAL, GLOBAL, SCRIPT, FUNCTION, TYPE } private static final boolean DEBUG = false; protected static class FinalCAstSymbol implements CAstSymbol { private final String _name; private final CAstType type; public FinalCAstSymbol(String _name, CAstType type) { this._name = _name; this.type = type; assert _name != null; assert type != null; } @Override public CAstType type() { return type; } @Override public String name() { return _name; } @Override public boolean isFinal() { return true; } @Override public boolean isCaseInsensitive() { return false; } @Override public boolean isInternalName() { return false; } @Override public Object defaultInitValue() { return null; } } public static class InternalCAstSymbol extends CAstSymbolImplBase { public InternalCAstSymbol(String _name, CAstType type) { super(_name, type, false, false, null); } public InternalCAstSymbol(String _name, CAstType type, boolean _isFinal) { super(_name, type, _isFinal, false, null); } public InternalCAstSymbol( String _name, CAstType type, boolean _isFinal, boolean _isCaseInsensitive) { super(_name, type, _isFinal, _isCaseInsensitive, null); } public InternalCAstSymbol( String _name, CAstType type, boolean _isFinal, boolean _isCaseInsensitive, Object _defaultInitValue) { super(_name, type, _isFinal, _isCaseInsensitive, _defaultInitValue); } @Override public boolean isInternalName() { return true; } } /** * interface for name information stored in a symbol table. * * @see Scope */ protected interface Symbol { int valueNumber(); Scope getDefiningScope(); boolean isParameter(); Object constant(); void setConstant(Object s); boolean isFinal(); boolean isGlobal(); boolean isInternalName(); Object defaultInitValue(); CAstType type(); } /** a scope in the symbol table built during AST traversal */ public interface Scope { ScopeType type(); int allocateTempValue(); int getConstantValue(Object c); boolean isConstant(int valueNumber); Object getConstantObject(int valueNumber); void declare(CAstSymbol s); void declare(CAstSymbol s, int valueNumber); boolean isCaseInsensitive(String name); boolean contains(String name); Symbol lookup(String name); Iterator<String> getAllNames(); int size(); boolean isGlobal(Symbol s); boolean isLexicallyScoped(Symbol s); CAstEntity getEntity(); Scope getParent(); } public abstract static class AbstractSymbol implements Symbol { private Object constantValue; private final boolean isFinalValue; private final Scope definingScope; private final Object defaultValue; protected AbstractSymbol(Scope definingScope, boolean isFinalValue, Object defaultValue) { this.definingScope = definingScope; this.isFinalValue = isFinalValue; this.defaultValue = defaultValue; } @Override public boolean isFinal() { return isFinalValue; } @Override public Object defaultInitValue() { return defaultValue; } @Override public Object constant() { return constantValue; } @Override public void setConstant(Object cv) { constantValue = cv; } @Override public Scope getDefiningScope() { return definingScope; } } public abstract class AbstractScope implements Scope { private final Scope parent; private final Map<String, Symbol> values = new LinkedHashMap<>(); private final Map<String, String> caseInsensitiveNames = new LinkedHashMap<>(); protected abstract SymbolTable getUnderlyingSymtab(); @Override public Scope getParent() { return parent; } @Override public int size() { return getUnderlyingSymtab().getMaxValueNumber() + 1; } @Override public Iterator<String> getAllNames() { return values.keySet().iterator(); } @Override public int allocateTempValue() { return getUnderlyingSymtab().newSymbol(); } @Override public int getConstantValue(Object o) { if (o instanceof Integer) { return getUnderlyingSymtab().getConstant((Integer) o); } else if (o instanceof Float) { return getUnderlyingSymtab().getConstant((Float) o); } else if (o instanceof Double) { return getUnderlyingSymtab().getConstant((Double) o); } else if (o instanceof Long) { return getUnderlyingSymtab().getConstant((Long) o); } else if (o instanceof String) { return getUnderlyingSymtab().getConstant((String) o); } else if (o instanceof Boolean) { return getUnderlyingSymtab().getConstant((Boolean) o); } else if (o instanceof Character) { return getUnderlyingSymtab().getConstant((Character) o); } else if (o instanceof Byte) { return getUnderlyingSymtab().getConstant((Byte) o); } else if (o instanceof Short) { return getUnderlyingSymtab().getConstant((Short) o); } else if (o == null) { return getUnderlyingSymtab().getNullConstant(); } else if (o == CAstControlFlowMap.SWITCH_DEFAULT) { return getUnderlyingSymtab().getConstant("__default label"); } else { return getUnderlyingSymtab().getOtherConstant(o); } } @Override public boolean isConstant(int valueNumber) { return getUnderlyingSymtab().isConstant(valueNumber); } @Override public Object getConstantObject(int valueNumber) { return getUnderlyingSymtab().getConstantValue(valueNumber); } @Override public void declare(CAstSymbol s, int vn) { String nm = s.name(); if (!contains(nm)) { if (s.isCaseInsensitive()) caseInsensitiveNames.put(nm.toLowerCase(), nm); values.put(nm, makeSymbol(s, vn)); } else { assert hasImplicitGlobals(); assert isGlobal(lookup(nm)); } } @Override public void declare(CAstSymbol s) { String nm = s.name(); if (!contains(nm) || lookup(nm).getDefiningScope() != this) { if (s.isCaseInsensitive()) caseInsensitiveNames.put(nm.toLowerCase(), nm); values.put(nm, makeSymbol(s)); } else { assert !s.isFinal() : "trying to redeclare " + nm; } } protected AbstractScope(Scope parent) { this.parent = parent; } private final String mapName(String nm) { String mappedName = caseInsensitiveNames.get(nm.toLowerCase()); return (mappedName == null) ? nm : mappedName; } protected Symbol makeSymbol(CAstSymbol s) { return makeSymbol( s.name(), s.type(), s.isFinal(), s.isInternalName(), s.defaultInitValue(), -1, this); } protected Symbol makeSymbol(CAstSymbol s, int vn) { return makeSymbol( s.name(), s.type(), s.isFinal(), s.isInternalName(), s.defaultInitValue(), vn, this); } protected abstract Symbol makeSymbol( String nm, CAstType type, boolean isFinal, boolean isInternalName, Object defaultInitValue, int vn, Scope parent); @Override public boolean isCaseInsensitive(String nm) { return caseInsensitiveNames.containsKey(nm.toLowerCase()); } @Override public Symbol lookup(String nm) { if (contains(nm)) { return values.get(mapName(nm)); } else { Symbol scoped = parent.lookup(nm); if (scoped != null && getEntityScope() == this && (isGlobal(scoped) || isLexicallyScoped(scoped))) { values.put( nm, makeSymbol( nm, scoped.type(), scoped.isFinal(), scoped.isInternalName(), scoped.defaultInitValue(), -1, scoped.getDefiningScope())); if (scoped.getDefiningScope().isCaseInsensitive(nm)) { caseInsensitiveNames.put(nm.toLowerCase(), nm); } return values.get(nm); } else { return scoped; } } } @Override public boolean contains(String nm) { String mappedName = caseInsensitiveNames.get(nm.toLowerCase()); return values.containsKey(mappedName == null ? nm : mappedName); } @Override public boolean isGlobal(Symbol s) { return s.getDefiningScope().type() == ScopeType.GLOBAL; } @Override public abstract boolean isLexicallyScoped(Symbol s); protected abstract AbstractScope getEntityScope(); @Override public abstract CAstEntity getEntity(); } protected AbstractScope makeScriptScope(final CAstEntity s, Scope parent) { return new AbstractScope(parent) { final SymbolTable scriptGlobalSymtab = new SymbolTable(s.getArgumentCount()); @Override public SymbolTable getUnderlyingSymtab() { return scriptGlobalSymtab; } @Override protected AbstractScope getEntityScope() { return this; } @Override public boolean isLexicallyScoped(Symbol s) { if (isGlobal(s)) return false; else return ((AbstractScope) s.getDefiningScope()).getEntity() != getEntity(); } @Override public CAstEntity getEntity() { return s; } @Override public ScopeType type() { return ScopeType.SCRIPT; } @Override protected Symbol makeSymbol( final String nm, final CAstType type, final boolean isFinal, final boolean isInternalName, final Object defaultInitValue, int vn, Scope definer) { assert nm != null; assert type != null; final int v = vn == -1 ? getUnderlyingSymtab().newSymbol() : vn; if (useDefaultInitValues() && defaultInitValue != null) { if (getUnderlyingSymtab().getValue(v) == null) { setDefaultValue(getUnderlyingSymtab(), v, defaultInitValue); } } return new AbstractSymbol(definer, isFinal, defaultInitValue) { @Override public String toString() { return nm + ':' + System.identityHashCode(this); } @Override public CAstType type() { return type; } @Override public int valueNumber() { return v; } @Override public boolean isInternalName() { return isInternalName; } @Override public boolean isParameter() { return false; } @Override public boolean isGlobal() { return false; } }; } }; } protected int getArgumentCount(CAstEntity f) { return f.getArgumentCount(); } protected String[] getArgumentNames(CAstEntity f) { return f.getArgumentNames(); } private AbstractScope makeFunctionScope(final CAstEntity f, Scope parent) { return new AbstractScope(parent) { private final String[] params = getArgumentNames(f); private final SymbolTable functionSymtab = new SymbolTable(getArgumentCount(f)); @Override public String toString() { return "scope for " + f.getName(); } // ctor for scope object { for (int i = 0; i < getArgumentCount(f); i++) { final int yuck = i; declare( new CAstSymbol() { @Override public String name() { return params[yuck]; } @Override public CAstType type() { if (f.getType() instanceof CAstType.Method) { if (yuck == 0) { return ((CAstType.Method) f.getType()).getDeclaringType(); } else { return ((CAstType.Method) f.getType()).getArgumentTypes().get(yuck - 1); } } else if (f.getType() instanceof CAstType.Function) { return ((CAstType.Function) f.getType()).getArgumentTypes().get(yuck); } else { return topType(); } } @Override public boolean isFinal() { return false; } @Override public boolean isCaseInsensitive() { return false; } @Override public boolean isInternalName() { return false; } @Override public Object defaultInitValue() { return null; } }); } } @Override public SymbolTable getUnderlyingSymtab() { return functionSymtab; } @Override protected AbstractScope getEntityScope() { return this; } @Override public boolean isLexicallyScoped(Symbol s) { if (isGlobal(s)) return false; else return ((AbstractScope) s.getDefiningScope()).getEntity() != getEntity(); } @Override public CAstEntity getEntity() { return f; } @Override public ScopeType type() { return ScopeType.FUNCTION; } private int find(String n) { for (int i = 0; i < params.length; i++) { if (n.equals(params[i])) { return i + 1; } } return -1; } @Override protected Symbol makeSymbol( final String nm, final CAstType type, final boolean isFinal, final boolean isInternalName, final Object defaultInitValue, final int valueNumber, Scope definer) { assert nm != null; assert type != null; return new AbstractSymbol(definer, isFinal, defaultInitValue) { final int vn; { int x = find(nm); if (x != -1) { assert valueNumber == -1; vn = x; } else if (valueNumber != -1) { vn = valueNumber; } else { vn = getUnderlyingSymtab().newSymbol(); } if (useDefaultInitValues() && defaultInitValue != null) { if (getUnderlyingSymtab().getValue(vn) == null) { setDefaultValue(getUnderlyingSymtab(), vn, defaultInitValue); } } } @Override public CAstType type() { return type; } @Override public String toString() { return nm + ':' + System.identityHashCode(this); } @Override public int valueNumber() { return vn; } @Override public boolean isInternalName() { return isInternalName; } @Override public boolean isParameter() { return vn <= params.length; } @Override public boolean isGlobal() { return false; } }; } }; } private Scope makeLocalScope(final Scope parent) { return new AbstractScope(parent) { @Override public ScopeType type() { return ScopeType.LOCAL; } @Override public SymbolTable getUnderlyingSymtab() { return ((AbstractScope) parent).getUnderlyingSymtab(); } @Override protected AbstractScope getEntityScope() { return ((AbstractScope) parent).getEntityScope(); } @Override public boolean isLexicallyScoped(Symbol s) { return getEntityScope().isLexicallyScoped(s); } @Override public CAstEntity getEntity() { return getEntityScope().getEntity(); } @Override protected Symbol makeSymbol( final String nm, final CAstType type, boolean isFinal, final boolean isInternalName, final Object defaultInitValue, int vn, Scope definer) { final int v = vn == -1 ? getUnderlyingSymtab().newSymbol() : vn; if (useDefaultInitValues() && defaultInitValue != null) { if (getUnderlyingSymtab().getValue(v) == null) { setDefaultValue(getUnderlyingSymtab(), v, defaultInitValue); } } assert nm != null; assert type != null; return new AbstractSymbol(definer, isFinal, defaultInitValue) { @Override public String toString() { return nm + ':' + System.identityHashCode(this); } @Override public CAstType type() { return type; } @Override public int valueNumber() { return v; } @Override public boolean isInternalName() { return isInternalName; } @Override public boolean isParameter() { return false; } @Override public boolean isGlobal() { return false; } }; } }; } private Scope makeGlobalScope() { final Map<String, AbstractSymbol> globalSymbols = new LinkedHashMap<>(); final Map<String, String> caseInsensitiveNames = new LinkedHashMap<>(); return new Scope() { @Override public String toString() { return "global scope"; } private String mapName(String nm) { String mappedName = caseInsensitiveNames.get(nm.toLowerCase()); return (mappedName == null) ? nm : mappedName; } @Override public Scope getParent() { return null; } @Override public boolean isGlobal(Symbol s) { return true; } @Override public boolean isLexicallyScoped(Symbol s) { return false; } @Override public CAstEntity getEntity() { return null; } @Override public int size() { return globalSymbols.size(); } @Override public Iterator<String> getAllNames() { return globalSymbols.keySet().iterator(); } @Override public int allocateTempValue() { throw new UnsupportedOperationException(); } @Override public int getConstantValue(Object c) { throw new UnsupportedOperationException(); } @Override public boolean isConstant(int valueNumber) { throw new UnsupportedOperationException(); } @Override public Object getConstantObject(int valueNumber) { throw new UnsupportedOperationException(); } @Override public ScopeType type() { return ScopeType.GLOBAL; } @Override public boolean contains(String name) { return hasImplicitGlobals() || globalSymbols.containsKey(mapName(name)); } @Override public boolean isCaseInsensitive(String name) { return caseInsensitiveNames.containsKey(name.toLowerCase()); } @Override public Symbol lookup(final String name) { if (!globalSymbols.containsKey(mapName(name))) { if (hasImplicitGlobals()) { declare( new CAstSymbol() { @Override public String name() { return name; } @Override public boolean isFinal() { return false; } @Override public boolean isCaseInsensitive() { return false; } @Override public boolean isInternalName() { return false; } @Override public Object defaultInitValue() { return null; } @Override public CAstType type() { return topType(); } }); } else if (hasSpecialUndeclaredVariables()) { return null; } else { throw new UnimplementedError("cannot find " + name); } } return globalSymbols.get(mapName(name)); } @Override public void declare(CAstSymbol s, int vn) { assert vn == -1; declare(s); } @Override public void declare(final CAstSymbol s) { final String name = s.name(); if (s.isCaseInsensitive()) { caseInsensitiveNames.put(name.toLowerCase(), name); } globalSymbols.put( name, new AbstractSymbol(this, s.isFinal(), s.defaultInitValue()) { @Override public String toString() { return name + ':' + System.identityHashCode(this); } @Override public CAstType type() { return s.type(); } @Override public boolean isParameter() { return false; } @Override public boolean isInternalName() { return s.isInternalName(); } @Override public int valueNumber() { throw new UnsupportedOperationException(); } @Override public boolean isGlobal() { return true; } }); } }; } protected Scope makeTypeScope(final CAstEntity type, final Scope parent) { final Map<String, AbstractSymbol> typeSymbols = new LinkedHashMap<>(); final Map<String, String> caseInsensitiveNames = new LinkedHashMap<>(); return new Scope() { private String mapName(String nm) { String mappedName = caseInsensitiveNames.get(nm.toLowerCase()); return (mappedName == null) ? nm : mappedName; } @Override public Scope getParent() { return parent; } @Override public boolean isGlobal(Symbol s) { return false; } @Override public boolean isLexicallyScoped(Symbol s) { return false; } @Override public CAstEntity getEntity() { return type; } @Override public int size() { return typeSymbols.size(); } @Override public Iterator<String> getAllNames() { return typeSymbols.keySet().iterator(); } @Override public int allocateTempValue() { throw new UnsupportedOperationException(); } @Override public int getConstantValue(Object c) { throw new UnsupportedOperationException(); } @Override public boolean isConstant(int valueNumber) { throw new UnsupportedOperationException(); } @Override public Object getConstantObject(int valueNumber) { throw new UnsupportedOperationException(); } @Override public ScopeType type() { return ScopeType.TYPE; } @Override public boolean contains(String name) { return typeSymbols.containsKey(mapName(name)); } @Override public boolean isCaseInsensitive(String name) { return caseInsensitiveNames.containsKey(name.toLowerCase()); } @Override public Symbol lookup(String nm) { if (typeSymbols.containsKey(mapName(nm))) return typeSymbols.get(mapName(nm)); else { return parent.lookup(nm); } } @Override public void declare(CAstSymbol s, int vn) { assert vn == -1; declare(s); } @Override public void declare(final CAstSymbol s) { final String name = s.name(); assert !s.isFinal(); if (s.isCaseInsensitive()) caseInsensitiveNames.put(name.toLowerCase(), name); typeSymbols.put( name, new AbstractSymbol(this, s.isFinal(), s.defaultInitValue()) { @Override public String toString() { return name + ':' + System.identityHashCode(this); } @Override public CAstType type() { return s.type(); } @Override public boolean isParameter() { return false; } @Override public boolean isInternalName() { return s.isInternalName(); } @Override public int valueNumber() { throw new UnsupportedOperationException(); } @Override public boolean isGlobal() { return false; } }); } }; } public interface WalkContext extends CAstVisitor.Context { WalkContext codeContext(); ModuleEntry getModule(); String getName(); String file(); @Override CAstSourcePositionMap getSourceMap(); CAstControlFlowMap getControlFlow(); Scope currentScope(); Set<Scope> entityScopes(); IncipientCFG cfg(); UnwindState getUnwindState(); void setCatchType(IBasicBlock<SSAInstruction> bb, TypeReference catchType); void setCatchType(CAstNode catchNode, TypeReference catchType); Map<IBasicBlock<SSAInstruction>, TypeReference[]> getCatchTypes(); void addEntityName(CAstEntity e, String name); String getEntityName(CAstEntity e); boolean hasValue(CAstNode n); int setValue(CAstNode n, int v); int getValue(CAstNode n); Set<Pair<Pair<String, String>, Integer>> exposeNameSet(CAstEntity entity, boolean writeSet); Set<Access> getAccesses(CAstEntity e); Scope getGlobalScope(); } private abstract class DelegatingContext implements WalkContext { private final WalkContext parent; DelegatingContext(WalkContext parent) { this.parent = parent; } @Override public WalkContext codeContext() { return parent.codeContext(); } @Override public Set<Access> getAccesses(CAstEntity e) { return parent.getAccesses(e); } @Override public ModuleEntry getModule() { return parent.getModule(); } @Override public String getName() { return parent.getName(); } @Override public String file() { return parent.file(); } @Override public CAstEntity top() { return parent.top(); } @Override public CAstSourcePositionMap getSourceMap() { return parent.getSourceMap(); } @Override public CAstControlFlowMap getControlFlow() { return parent.getControlFlow(); } @Override public Scope currentScope() { return parent.currentScope(); } @Override public Set<Scope> entityScopes() { return parent.entityScopes(); } @Override public IncipientCFG cfg() { return parent.cfg(); } @Override public UnwindState getUnwindState() { return parent.getUnwindState(); } @Override public void setCatchType(IBasicBlock<SSAInstruction> bb, TypeReference catchType) { parent.setCatchType(bb, catchType); } @Override public void setCatchType(CAstNode catchNode, TypeReference catchType) { parent.setCatchType(catchNode, catchType); } @Override public Map<IBasicBlock<SSAInstruction>, TypeReference[]> getCatchTypes() { return parent.getCatchTypes(); } @Override public void addEntityName(CAstEntity e, String name) { parent.addEntityName(e, name); } @Override public String getEntityName(CAstEntity e) { return parent.getEntityName(e); } @Override public boolean hasValue(CAstNode n) { return parent.hasValue(n); } @Override public int setValue(CAstNode n, int v) { return parent.setValue(n, v); } @Override public int getValue(CAstNode n) { return parent.getValue(n); } @Override public Set<Pair<Pair<String, String>, Integer>> exposeNameSet( CAstEntity entity, boolean writeSet) { return parent.exposeNameSet(entity, writeSet); } @Override public Scope getGlobalScope() { return parent.getGlobalScope(); } } private class FileContext extends DelegatingContext { private final String fUnitName; public FileContext(WalkContext parent, String unitName) { super(parent); fUnitName = unitName; } @Override public String getName() { return fUnitName; } } private class UnwindContext extends DelegatingContext { private final UnwindState state; UnwindContext(CAstNode unwindNode, WalkContext parent, CAstVisitor<WalkContext> visitor) { super(parent); this.state = new UnwindState(unwindNode, parent, visitor); } @Override public UnwindState getUnwindState() { return state; } } private abstract class EntityContext extends DelegatingContext { protected final CAstEntity topNode; protected final String name; EntityContext(WalkContext parent, CAstEntity s) { super(parent); this.topNode = s; this.name = composeEntityName(parent, s); addEntityName(s, this.name); } @Override public String getName() { return name; } @Override public CAstEntity top() { return topNode; } @Override public CAstSourcePositionMap getSourceMap() { return top().getSourceMap(); } } public class CodeEntityContext extends EntityContext { private final Scope topEntityScope; private final Set<Scope> allEntityScopes; private final IncipientCFG cfg; private final Map<IBasicBlock<SSAInstruction>, TypeReference[]> catchTypes = HashMapFactory.make(); Set<Pair<Pair<String, String>, Integer>> exposedReads; Set<Pair<Pair<String, String>, Integer>> exposedWrites; Set<Access> accesses; /** * maps nodes in the current function to the value number holding their value or, for constants, * to their constant value. */ private final Map<CAstNode, Integer> results = new LinkedHashMap<>(); public CodeEntityContext(WalkContext parent, Scope entityScope, CAstEntity s) { super(parent, s); this.topEntityScope = entityScope; this.allEntityScopes = HashSetFactory.make(); this.allEntityScopes.add(entityScope); cfg = new IncipientCFG(); } @Override public WalkContext codeContext() { return this; } @Override public Set<Access> getAccesses(CAstEntity e) { if (e == topNode) { if (accesses == null) { accesses = HashSetFactory.make(); } return accesses; } else { return super.getAccesses(e); } } @Override public Set<Pair<Pair<String, String>, Integer>> exposeNameSet( CAstEntity entity, boolean writeSet) { if (entity == topNode) { if (writeSet) { if (exposedWrites == null) { exposedWrites = HashSetFactory.make(); } return exposedWrites; } else { if (exposedReads == null) { exposedReads = HashSetFactory.make(); } return exposedReads; } } else { return super.exposeNameSet(entity, writeSet); } } @Override public CAstControlFlowMap getControlFlow() { return top().getControlFlow(); } @Override public IncipientCFG cfg() { return cfg; } @Override public Scope currentScope() { return topEntityScope; } @Override public Set<Scope> entityScopes() { return allEntityScopes; } @Override public UnwindState getUnwindState() { return null; } @Override public void setCatchType(CAstNode catchNode, TypeReference catchType) { setCatchType(cfg.getBlock(catchNode), catchType); } @Override public void setCatchType(IBasicBlock<SSAInstruction> bb, TypeReference catchType) { if (!catchTypes.containsKey(bb)) { catchTypes.put(bb, new TypeReference[] {catchType}); } else { TypeReference[] data = catchTypes.get(bb); for (TypeReference element : data) { if (element == catchType) { return; } } TypeReference[] newData = Arrays.copyOf(data, data.length + 1); newData[data.length] = catchType; catchTypes.put(bb, newData); } } @Override public Map<IBasicBlock<SSAInstruction>, TypeReference[]> getCatchTypes() { return catchTypes; } @Override public boolean hasValue(CAstNode n) { return results.containsKey(n); } @Override public final int setValue(CAstNode n, int v) { results.put(n, v); return v; } @Override public final int getValue(CAstNode n) { if (results.containsKey(n)) return results.get(n); else { if (DEBUG) { System.err.println(("no value for " + n.getKind())); } return -1; } } } protected final class TypeContext extends EntityContext { private TypeContext(WalkContext parent, CAstEntity n) { super(parent, n); } @Override public CAstControlFlowMap getControlFlow() { Assertions.UNREACHABLE("TypeContext.getControlFlow()"); return null; } @Override public IncipientCFG cfg() { Assertions.UNREACHABLE("TypeContext.cfg()"); return null; } @Override public UnwindState getUnwindState() { Assertions.UNREACHABLE("TypeContext.getUnwindState()"); return null; } } private class LocalContext extends DelegatingContext { private final Scope localScope; LocalContext(WalkContext parent, Scope localScope) { super(parent); this.localScope = localScope; parent.entityScopes().add(localScope); } @Override public Scope currentScope() { return localScope; } } /** * lexical access information for some entity scope. used during call graph construction to handle * lexical accesses. */ public static class AstLexicalInformation implements LexicalInformation { /** the name of this function, as it appears in the definer portion of a lexical name */ private final String functionLexicalName; /** * names possibly accessed in a nested lexical scope, represented as pairs * (name,nameOfDefiningEntity) */ private final Pair<String, String>[] exposedNames; /** * map from instruction index and exposed name (via its index in {@link #exposedNames}) to the * value number for the name at that instruction index. This can vary at different instructions * due to SSA (and this information is updated during {@link SSAConversion}). */ private final int[][] instructionLexicalUses; /** * maps each exposed name (via its index in {@link #exposedNames}) to its value number at method * exit. */ private final int[] exitLexicalUses; /** * the names of the enclosing methods declaring names that are lexically accessed by the entity */ private final String[] scopingParents; /** * all value numbers appearing as entries in {@link #instructionLexicalUses} and {@link * #exitLexicalUses}, computed lazily */ private MutableIntSet allExposedUses = null; /** names of exposed variables of this method that cannot be written outside */ private final Set<String> readOnlyNames; @SuppressWarnings("unchecked") public AstLexicalInformation(AstLexicalInformation original) { this.functionLexicalName = original.functionLexicalName; if (original.exposedNames != null) { exposedNames = new Pair[original.exposedNames.length]; for (int i = 0; i < exposedNames.length; i++) { exposedNames[i] = Pair.make(original.exposedNames[i].fst, original.exposedNames[i].snd); } } else { exposedNames = null; } instructionLexicalUses = new int[original.instructionLexicalUses.length][]; for (int i = 0; i < instructionLexicalUses.length; i++) { int[] x = original.instructionLexicalUses[i]; if (x != null) { instructionLexicalUses[i] = x.clone(); } } if (original.exitLexicalUses != null) { exitLexicalUses = new int[original.exitLexicalUses.length]; System.arraycopy(original.exitLexicalUses, 0, exitLexicalUses, 0, exitLexicalUses.length); } else { exitLexicalUses = null; } if (original.scopingParents != null) { scopingParents = new String[original.scopingParents.length]; System.arraycopy(original.scopingParents, 0, scopingParents, 0, scopingParents.length); } else { scopingParents = null; } readOnlyNames = original.readOnlyNames; } private static int[] buildLexicalUseArray( Pair<Pair<String, String>, Integer>[] exposedNames, String entityName) { if (exposedNames != null) { int[] lexicalUses = new int[exposedNames.length]; for (int j = 0; j < exposedNames.length; j++) { if (entityName == null || entityName.equals(exposedNames[j].fst.snd)) { lexicalUses[j] = exposedNames[j].snd; } else { lexicalUses[j] = -1; } } return lexicalUses; } else { return null; } } private static Pair<String, String>[] buildLexicalNamesArray( Pair<Pair<String, String>, Integer>[] exposedNames) { if (exposedNames != null) { @SuppressWarnings("unchecked") Pair<String, String>[] lexicalNames = new Pair[exposedNames.length]; for (int j = 0; j < exposedNames.length; j++) { lexicalNames[j] = exposedNames[j].fst; } return lexicalNames; } else { return null; } } AstLexicalInformation( String entityName, Scope scope, SSAInstruction[] instrs, Set<Pair<Pair<String, String>, Integer>> exposedNamesForReadSet, Set<Pair<Pair<String, String>, Integer>> exposedNamesForWriteSet, Set<Access> accesses) { this.functionLexicalName = entityName; Pair<Pair<String, String>, Integer>[] EN = null; if (exposedNamesForReadSet != null || exposedNamesForWriteSet != null) { Set<Pair<Pair<String, String>, Integer>> exposedNamesSet = new HashSet<>(); if (exposedNamesForReadSet != null) { exposedNamesSet.addAll(exposedNamesForReadSet); } if (exposedNamesForWriteSet != null) { exposedNamesSet.addAll(exposedNamesForWriteSet); } EN = exposedNamesSet.toArray(new Pair[0]); } if (exposedNamesForReadSet != null) { Set<String> readOnlyNames = new HashSet<>(); for (Pair<Pair<String, String>, Integer> v : exposedNamesForReadSet) { if (entityName != null && entityName.equals(v.fst.snd)) { readOnlyNames.add(v.fst.fst); } } if (exposedNamesForWriteSet != null) { for (Pair<Pair<String, String>, Integer> v : exposedNamesForWriteSet) { if (entityName != null && entityName.equals(v.fst.snd)) { readOnlyNames.remove(v.fst.fst); } } } this.readOnlyNames = readOnlyNames; } else { this.readOnlyNames = null; } this.exposedNames = buildLexicalNamesArray(EN); // the value numbers stored in exitLexicalUses and instructionLexicalUses // are identical at first; they will be updated // as needed during the final SSA conversion this.exitLexicalUses = buildLexicalUseArray(EN, entityName); this.instructionLexicalUses = new int[instrs.length][]; for (int i = 0; i < instrs.length; i++) { if (instrs[i] instanceof SSAAbstractInvokeInstruction) { this.instructionLexicalUses[i] = buildLexicalUseArray(EN, null); } } if (accesses != null) { Set<String> parents = new LinkedHashSet<>(); for (Access AC : accesses) { if (AC.variableDefiner != null) { parents.add(AC.variableDefiner); } } scopingParents = parents.toArray(new String[0]); if (DEBUG_LEXICAL) { System.err.println(("scoping parents of " + scope.getEntity())); System.err.println(parents.toString()); } } else { scopingParents = null; } if (DEBUG_NAMES) { System.err.println(("lexical uses of " + scope.getEntity())); for (int i = 0; i < instructionLexicalUses.length; i++) { if (instructionLexicalUses[i] != null) { System.err.println((" lexical uses of " + instrs[i])); for (int j = 0; j < instructionLexicalUses[i].length; j++) { System.err.println( (" " + this.exposedNames[j].fst + ": " + instructionLexicalUses[i][j])); } } } } } @Override public int[] getExitExposedUses() { return exitLexicalUses; } private static final int[] NONE = new int[0]; @Override public int[] getExposedUses(int instructionOffset) { return instructionLexicalUses[instructionOffset] == null ? NONE : instructionLexicalUses[instructionOffset]; } @Override public IntSet getAllExposedUses() { if (allExposedUses == null) { allExposedUses = IntSetUtil.make(); if (exitLexicalUses != null) { for (int exitLexicalUse : exitLexicalUses) { if (exitLexicalUse > 0) { allExposedUses.add(exitLexicalUse); } } } if (instructionLexicalUses != null) { for (int[] instructionLexicalUse : instructionLexicalUses) { if (instructionLexicalUse != null) { for (int element : instructionLexicalUse) { if (element > 0) { allExposedUses.add(element); } } } } } } return allExposedUses; } @Override public Pair<String, String>[] getExposedNames() { return exposedNames; } @Override public String[] getScopingParents() { return scopingParents; } @Override public boolean isReadOnly(String name) { return readOnlyNames != null && readOnlyNames.contains(name); } @Override public String getScopingName() { return functionLexicalName; } public static boolean hasExposedUses(CGNode caller, CallSiteReference site) { int uses[] = ((AstMethod) caller.getMethod()).lexicalInfo().getExposedUses(site.getProgramCounter()); if (uses != null) { for (int use : uses) { if (use > 0) { return true; } } } return false; } } /** record that in entity e, the access is performed. */ private static void addAccess(WalkContext context, CAstEntity e, Access access) { context.getAccesses(e).add(access); } /** * Record that a name assigned a value number in the scope of entity may be accessed by a * lexically nested scope, i.e., the name may be <em>exposed</em> to lexically nested scopes. This * information is needed during call graph construction to properly model the data flow due to the * access in the nested scope. * * @param entity an entity in whose scope name is assigned a value number * @param declaration the declaring entity for name (possibly an enclosing scope of entity) * @param name the accessed name * @param valueNumber the name's value number in the scope of entity */ private static void addExposedName( CAstEntity entity, CAstEntity declaration, String name, int valueNumber, boolean isWrite, WalkContext context) { Pair<Pair<String, String>, Integer> newVal = Pair.make(Pair.make(name, context.getEntityName(declaration)), valueNumber); context.exposeNameSet(entity, isWrite).add(newVal); } @Override protected WalkContext getCodeContext(WalkContext context) { return context.codeContext(); } public void setDefaultValue(SymbolTable symtab, int vn, Object value) { if (value == CAstSymbol.NULL_DEFAULT_VALUE) { symtab.setDefaultValue(vn, null); } else { symtab.setDefaultValue(vn, value); } } protected IUnaryOpInstruction.IOperator translateUnaryOpcode(CAstNode op) { if (op == CAstOperator.OP_BITNOT) return CAstUnaryOp.BITNOT; else if (op == CAstOperator.OP_NOT) return IUnaryOpInstruction.Operator.NEG; else if (op == CAstOperator.OP_SUB) return CAstUnaryOp.MINUS; else if (op == CAstOperator.OP_ADD) return CAstUnaryOp.PLUS; else Assertions.UNREACHABLE("cannot translate " + CAstPrinter.print(op)); return null; } protected IBinaryOpInstruction.IOperator translateBinaryOpcode(CAstNode op) { if (op == CAstOperator.OP_ADD) return BinaryOpInstruction.Operator.ADD; else if (op == CAstOperator.OP_DIV) return BinaryOpInstruction.Operator.DIV; else if (op == CAstOperator.OP_LSH) return ShiftInstruction.Operator.SHL; else if (op == CAstOperator.OP_MOD) return BinaryOpInstruction.Operator.REM; else if (op == CAstOperator.OP_MUL) return BinaryOpInstruction.Operator.MUL; else if (op == CAstOperator.OP_RSH) return ShiftInstruction.Operator.SHR; else if (op == CAstOperator.OP_SUB) return BinaryOpInstruction.Operator.SUB; else if (op == CAstOperator.OP_URSH) return ShiftInstruction.Operator.USHR; else if (op == CAstOperator.OP_BIT_AND) return BinaryOpInstruction.Operator.AND; else if (op == CAstOperator.OP_BIT_OR) return BinaryOpInstruction.Operator.OR; else if (op == CAstOperator.OP_BIT_XOR) return BinaryOpInstruction.Operator.XOR; else if (op == CAstOperator.OP_CONCAT) return CAstBinaryOp.CONCAT; else if (op == CAstOperator.OP_EQ) return CAstBinaryOp.EQ; else if (op == CAstOperator.OP_STRICT_EQ) return CAstBinaryOp.STRICT_EQ; else if (op == CAstOperator.OP_GE) return CAstBinaryOp.GE; else if (op == CAstOperator.OP_GT) return CAstBinaryOp.GT; else if (op == CAstOperator.OP_LE) return CAstBinaryOp.LE; else if (op == CAstOperator.OP_LT) return CAstBinaryOp.LT; else if (op == CAstOperator.OP_NE) return CAstBinaryOp.NE; else if (op == CAstOperator.OP_STRICT_NE) return CAstBinaryOp.STRICT_NE; else { Assertions.UNREACHABLE("cannot translate " + CAstPrinter.print(op)); return null; } } protected IConditionalBranchInstruction.IOperator translateConditionOpcode(CAstNode op) { if (op == CAstOperator.OP_EQ) return ConditionalBranchInstruction.Operator.EQ; else if (op == CAstOperator.OP_GE) return ConditionalBranchInstruction.Operator.GE; else if (op == CAstOperator.OP_GT) return ConditionalBranchInstruction.Operator.GT; else if (op == CAstOperator.OP_LE) return ConditionalBranchInstruction.Operator.LE; else if (op == CAstOperator.OP_LT) return ConditionalBranchInstruction.Operator.LT; else if (op == CAstOperator.OP_NE) return ConditionalBranchInstruction.Operator.NE; else { assert false : "cannot translate " + CAstPrinter.print(op); return null; } } protected String[] makeNameMap( CAstEntity n, Set<Scope> scopes, @SuppressWarnings("unused") SSAInstruction[] insts) { // all scopes share the same underlying symtab, which is what // size really refers to. String[] map = new String[scopes.iterator().next().size() + 1]; if (DEBUG_NAMES) { System.err.println(("names array of size " + map.length)); } for (Scope scope : scopes) { for (String nm : Iterator2Iterable.make(scope.getAllNames())) { if (ignoreName(nm)) { continue; } Symbol v = scope.lookup(nm); if (v.isInternalName()) { continue; } // constants can flow to multiple variables if (scope.isConstant(v.valueNumber())) continue; assert map[v.valueNumber()] == null || map[v.valueNumber()].equals(nm) || ignoreName(map[v.valueNumber()]) : "value number " + v.valueNumber() + " mapped to multiple names in " + n.getName() + ": " + nm + " and " + map[v.valueNumber()]; map[v.valueNumber()] = nm; if (DEBUG_NAMES) { System.err.println(("mapping name " + nm + " to " + v.valueNumber())); } } } return map; } protected static final CAstType getTypeForNode(WalkContext context, CAstNode node) { if (context.top().getNodeTypeMap() != null) { return context.top().getNodeTypeMap().getNodeType(node); } else { return null; } } private Position getPosition(CAstSourcePositionMap map, CAstNode n) { if (map.getPosition(n) != null) { return map.getPosition(n); } else { for (CAstNode child : n.getChildren()) { Position p = getPosition(map, child); if (p != null) { return p; } } return null; } } @Override protected WalkContext makeFileContext(WalkContext c, CAstEntity n) { return new FileContext(c, n.getName()); } @Override protected WalkContext makeTypeContext(WalkContext c, CAstEntity n) { return new TypeContext(c, n); } @Override protected WalkContext makeCodeContext(WalkContext context, CAstEntity n) { AbstractScope scope; if (n.getKind() == CAstEntity.SCRIPT_ENTITY) scope = makeScriptScope(n, context.currentScope()); else scope = makeFunctionScope(n, context.currentScope()); return new CodeEntityContext(context, scope, n); } @Override protected boolean enterEntity( final CAstEntity n, WalkContext context, CAstVisitor<WalkContext> visitor) { if (DEBUG_TOP) System.err.println(("translating " + n.getName())); return false; } @Override protected boolean visitFileEntity( CAstEntity n, WalkContext context, WalkContext fileContext, CAstVisitor<WalkContext> visitor) { /* empty */ return false; } @Override protected void leaveFileEntity( CAstEntity n, WalkContext context, WalkContext fileContext, CAstVisitor<WalkContext> visitor) { /* empty */ } @Override protected boolean visitFieldEntity( CAstEntity n, WalkContext context, CAstVisitor<WalkContext> visitor) { /* empty */ return false; } @Override protected void leaveFieldEntity( CAstEntity n, WalkContext context, CAstVisitor<WalkContext> visitor) { // Define a new field in the enclosing type, if the language we're // processing allows such. CAstEntity topEntity = context.top(); // better be a type assert topEntity.getKind() == CAstEntity.TYPE_ENTITY : "Parent of field entity is not a type???"; defineField(topEntity, context, n); } @Override protected boolean visitGlobalEntity( CAstEntity n, WalkContext context, CAstVisitor<WalkContext> visitor) { /* empty */ return false; } @Override protected void leaveGlobalEntity( CAstEntity n, WalkContext context, CAstVisitor<WalkContext> visitor) { // Define a new field in the enclosing type, if the language we're // processing allows such. context.getGlobalScope().declare(new CAstSymbolImpl(n.getName(), n.getType())); } @Override protected boolean visitTypeEntity( CAstEntity n, WalkContext context, WalkContext typeContext, CAstVisitor<WalkContext> visitor) { return !defineType(n, context); } @Override protected void leaveTypeEntity( CAstEntity n, WalkContext context, WalkContext typeContext, CAstVisitor<WalkContext> visitor) { /* empty */ } @Override protected boolean visitFunctionEntity( CAstEntity n, WalkContext context, WalkContext codeContext, CAstVisitor<WalkContext> visitor) { if (n.getAST() == null) // presumably abstract declareFunction(n, context); else { declareFunction(n, context); initFunctionEntity(n, codeContext); } return false; } @Override protected void leaveFunctionEntity( CAstEntity n, WalkContext context, WalkContext codeContext, CAstVisitor<WalkContext> visitor) { if (n.getAST() != null) // non-abstract closeFunctionEntity(n, context, codeContext); } @Override protected boolean visitMacroEntity( CAstEntity n, WalkContext context, WalkContext codeContext, CAstVisitor<WalkContext> visitor) { return true; } @Override protected boolean visitScriptEntity( CAstEntity n, WalkContext context, WalkContext codeContext, CAstVisitor<WalkContext> visitor) { declareFunction(n, codeContext); initFunctionEntity(n, codeContext); return false; } @Override protected void leaveScriptEntity( CAstEntity n, WalkContext context, WalkContext codeContext, CAstVisitor<WalkContext> visitor) { closeFunctionEntity(n, context, codeContext); } public void initFunctionEntity(CAstEntity n, WalkContext functionContext) { if (liftDeclarationsForLexicalScoping()) { Set<String> names = entity2ExposedNames.get(n); if (names != null) { for (String nm : names) { functionContext.currentScope().declare(new CAstSymbolImpl(nm, CAstType.DYNAMIC)); } } } // entry block functionContext.cfg().makeEntryBlock(functionContext.cfg().newBlock(false)); // first real block functionContext.cfg().newBlock(true); // prologue code, if any doPrologue(functionContext); } public void closeFunctionEntity( final CAstEntity n, WalkContext parentContext, WalkContext functionContext) { // exit block functionContext.cfg().makeExitBlock(functionContext.cfg().newBlock(true)); // create code entry stuff for this entity SymbolTable symtab = ((AbstractScope) functionContext.currentScope()).getUnderlyingSymtab(); Map<IBasicBlock<SSAInstruction>, TypeReference[]> catchTypes = functionContext.getCatchTypes(); AstCFG cfg = new AstCFG(n, functionContext.cfg(), symtab, insts); Position[] line = functionContext.cfg().getLinePositionMap(); Position[][] operand = functionContext.cfg().getOperandPositionMap(); boolean katch = functionContext.cfg().hasCatchBlock(); boolean monitor = functionContext.cfg().hasMonitorOp(); String[] nms = makeNameMap(n, functionContext.entityScopes(), cfg.getInstructions()); /* * Set reachableBlocks = DFS.getReachableNodes(cfg, * Collections.singleton(cfg.entry())); * Assertions._assert(reachableBlocks.size() == cfg.getNumberOfNodes(), * cfg.toString()); */ // (put here to allow subclasses to handle stuff in scoped entities) // assemble lexical information AstLexicalInformation LI = new AstLexicalInformation( functionContext.getEntityName(n), functionContext.currentScope(), cfg.getInstructions(), functionContext.exposeNameSet(n, false), functionContext.exposeNameSet(n, true), functionContext.getAccesses(n)); Position[] parameterPositions = getParameterPositions(n); DebuggingInformation DBG = new AstDebuggingInformation( n.getNamePosition(), n.getPosition(), line, operand, parameterPositions, nms, n.getSourceMap().positions()); // actually make code body defineFunction(n, parentContext, cfg, symtab, katch, catchTypes, monitor, LI, DBG); } protected abstract Position[] getParameterPositions(CAstEntity e); @Override protected WalkContext makeLocalContext(WalkContext context, CAstNode n) { return new LocalContext(context, makeLocalScope(context.currentScope())); } @Override protected WalkContext makeSpecialParentContext(final WalkContext context, CAstNode n) { final String specialName = (String) n.getChild(0).getValue(); return new LocalContext( context, new AbstractScope(context.currentScope()) { private Scope parent = null; private Scope parent() { if (parent == null) { parent = ((AbstractScope) context.currentScope()).getEntityScope().getParent(); } return parent; } @Override public ScopeType type() { return ScopeType.LOCAL; } private Scope scopeFor(String name) { if (name.equals(specialName)) { return parent(); } else { return context.currentScope(); } } @Override public boolean contains(String name) { return scopeFor(name).contains(name); } @Override public Symbol lookup(String name) { return scopeFor(name).lookup(name); } @Override protected SymbolTable getUnderlyingSymtab() { return ((AbstractScope) context.currentScope()).getUnderlyingSymtab(); } @Override protected Symbol makeSymbol( String nm, CAstType type, boolean isFinal, boolean isInternalName, Object defaultInitValue, int vn, Scope parent) { return ((AbstractScope) context.currentScope()) .makeSymbol(nm, type, isFinal, isInternalName, defaultInitValue, vn, parent); } @Override protected AbstractScope getEntityScope() { return ((AbstractScope) context.currentScope()).getEntityScope(); } @Override public boolean isLexicallyScoped(Symbol s) { return context.currentScope().isLexicallyScoped(s); } @Override public CAstEntity getEntity() { return context.top(); } }); } @Override protected WalkContext makeUnwindContext( WalkContext context, CAstNode n, CAstVisitor<WalkContext> visitor) { // here, n represents the "finally" block of the unwind return new UnwindContext(n, context, visitor); } protected Map<CAstEntity, Set<String>> entity2ExposedNames; protected Map<CAstEntity, Set<Pair<CAstEntity, String>>> entity2WrittenNames; protected int processFunctionExpr(CAstNode n, WalkContext context) { CAstEntity fn = (CAstEntity) n.getChild(0).getValue(); declareFunction(fn, context); int result = context.currentScope().allocateTempValue(); int ex = context.currentScope().allocateTempValue(); doMaterializeFunction(n, context, result, ex, fn); return result; } @Override protected boolean visitFunctionExpr(CAstNode n, WalkContext c, CAstVisitor<WalkContext> visitor) { /* empty */ return false; } @Override protected void leaveFunctionExpr(CAstNode n, WalkContext c, CAstVisitor<WalkContext> visitor) { int result = processFunctionExpr(n, c); c.setValue(n, result); } @Override protected boolean visitFunctionStmt(CAstNode n, WalkContext c, CAstVisitor<WalkContext> visitor) { /* empty */ return false; } @Override protected void leaveFunctionStmt( CAstNode n, WalkContext context, CAstVisitor<WalkContext> visitor) { int result = processFunctionExpr(n, context); CAstEntity fn = (CAstEntity) n.getChild(0).getValue(); // FIXME: handle redefinitions of functions Scope cs = context.currentScope(); if (cs.contains(fn.getName()) && !cs.isLexicallyScoped(cs.lookup(fn.getName())) && !cs.isGlobal(cs.lookup(fn.getName()))) { // if we already have a local with the function's name, write the function // value to that local assignValue(n, context, cs.lookup(fn.getName()), fn.getName(), result); } else if (topLevelFunctionsInGlobalScope() && context.top().getKind() == CAstEntity.SCRIPT_ENTITY) { context.getGlobalScope().declare(new FinalCAstSymbol(fn.getName(), fn.getType())); assignValue(n, context, cs.lookup(fn.getName()), fn.getName(), result); } else { context.currentScope().declare(new FinalCAstSymbol(fn.getName(), fn.getType()), result); } } @Override protected boolean visitLocalScope(CAstNode n, WalkContext c, CAstVisitor<WalkContext> visitor) { /* empty */ return false; } @Override protected boolean visitSpecialParentScope( CAstNode n, WalkContext c, CAstVisitor<WalkContext> visitor) { /* empty */ return false; } @Override protected void leaveLocalScope(CAstNode n, WalkContext c, CAstVisitor<WalkContext> visitor) { c.setValue(n, c.getValue(n.getChild(0))); } @Override protected void leaveSpecialParentScope( CAstNode n, WalkContext c, CAstVisitor<WalkContext> visitor) { c.setValue(n, c.getValue(n.getChild(1))); } @Override protected boolean visitBlockExpr(CAstNode n, WalkContext c, CAstVisitor<WalkContext> visitor) { /* empty */ return false; } @Override protected void leaveBlockExpr(CAstNode n, WalkContext c, CAstVisitor<WalkContext> visitor) { c.setValue(n, c.getValue(n.getChild(n.getChildCount() - 1))); } @Override protected boolean visitBlockStmt(CAstNode n, WalkContext c, CAstVisitor<WalkContext> visitor) { /* empty */ return false; } @Override protected void leaveBlockStmt(CAstNode n, WalkContext c, CAstVisitor<WalkContext> visitor) { /* empty */ } @Override protected boolean visitLoop(CAstNode n, WalkContext c, CAstVisitor<WalkContext> visitor) { WalkContext context = c; // loop test block context.cfg().newBlock(true); PreBasicBlock headerB = context.cfg().getCurrentBlock(); visitor.visit(n.getChild(0), context, visitor); assert c.getValue(n.getChild(0)) != -1 : "error in loop test " + CAstPrinter.print(n.getChild(0), context.top().getSourceMap()) + " of loop " + CAstPrinter.print(n, context.top().getSourceMap()); context .cfg() .addInstruction( insts.ConditionalBranchInstruction( context.cfg().currentInstruction, translateConditionOpcode(CAstOperator.OP_EQ), null, c.getValue(n.getChild(0)), context.currentScope().getConstantValue(0), -1)); PreBasicBlock branchB = context.cfg().getCurrentBlock(); // loop body context.cfg().newBlock(true); visitor.visit(n.getChild(1), context, visitor); if (!context.cfg().isDeadBlock(context.cfg().getCurrentBlock())) { context.cfg().addInstruction(insts.GotoInstruction(context.cfg().currentInstruction, -1)); PreBasicBlock bodyB = context.cfg().getCurrentBlock(); context.cfg().addEdge(bodyB, headerB); // next block context.cfg().newBlock(false); } PreBasicBlock nextB = context.cfg().getCurrentBlock(); // control flow mapping; context.cfg().addEdge(branchB, nextB); return true; } // Make final to prevent overriding @Override protected final void leaveLoopHeader( CAstNode n, WalkContext c, CAstVisitor<WalkContext> visitor) { /* empty */ } @Override protected final void leaveLoop(CAstNode n, WalkContext c, CAstVisitor<WalkContext> visitor) { /* empty */ } @Override protected boolean visitGetCaughtException( CAstNode n, WalkContext c, CAstVisitor<WalkContext> visitor) { /* empty */ return false; } @Override protected void leaveGetCaughtException( CAstNode n, WalkContext c, CAstVisitor<WalkContext> visitor) { WalkContext context = c; String nm = (String) n.getChild(0).getValue(); context.currentScope().declare(new FinalCAstSymbol(nm, exceptionType())); int v = context.currentScope().allocateTempValue(); context .cfg() .addInstruction( insts.GetCaughtExceptionInstruction( context.cfg().currentInstruction, context.cfg().getCurrentBlock().getNumber(), v)); context .cfg() .addInstruction( new AssignInstruction( context.cfg().currentInstruction, context.currentScope().lookup(nm).valueNumber(), v)); } @Override protected boolean visitThis(CAstNode n, WalkContext c, CAstVisitor<WalkContext> visitor) { /* empty */ return false; } @Override protected void leaveThis(CAstNode n, WalkContext c, CAstVisitor<WalkContext> visitor) { c.setValue(n, 1); } @Override protected boolean visitSuper(CAstNode n, WalkContext c, CAstVisitor<WalkContext> visitor) { /* empty */ return false; } @Override protected void leaveSuper(CAstNode n, WalkContext c, CAstVisitor<WalkContext> visitor) { c.setValue(n, 1); } @Override protected boolean visitCall(CAstNode n, WalkContext c, CAstVisitor<WalkContext> visitor) { WalkContext context = c; int result = context.currentScope().allocateTempValue(); c.setValue(n, result); return false; } @Override protected void leaveCall(CAstNode n, WalkContext c, CAstVisitor<WalkContext> visitor) { WalkContext context = c; int result = c.getValue(n); int exp = context.currentScope().allocateTempValue(); int fun = c.getValue(n.getChild(0)); CAstNode functionName = n.getChild(1); int[] args = new int[n.getChildCount() - 2]; for (int i = 0; i < args.length; i++) { args[i] = c.getValue(n.getChild(i + 2)); } doCall(context, n, result, exp, functionName, fun, args); } @Override protected boolean visitVar(CAstNode n, WalkContext c, CAstVisitor<WalkContext> visitor) { /* empty */ return false; } @Override protected void leaveVar(CAstNode n, WalkContext c, CAstVisitor<WalkContext> visitor) { WalkContext context = c; String nm = (String) n.getChild(0).getValue(); assert nm != null : "cannot find var for " + CAstPrinter.print(n, context.getSourceMap()); Symbol s = context.currentScope().lookup(nm); assert s != null : "cannot find symbol for " + nm + " at " + CAstPrinter.print(n, context.getSourceMap()); assert s.type() != null : "no type for " + nm + " at " + CAstPrinter.print(n, context.getSourceMap()); TypeReference type = makeType(s.type()); if (context.currentScope().isGlobal(s)) { c.setValue(n, doGlobalRead(n, context, nm, type)); } else if (context.currentScope().isLexicallyScoped(s)) { c.setValue(n, doLexicallyScopedRead(n, context, nm, type)); } else { c.setValue(n, doLocalRead(context, nm, type)); } } @Override protected boolean visitConstant(CAstNode n, WalkContext c, CAstVisitor<WalkContext> visitor) { /* empty */ return false; } @Override protected void leaveConstant(CAstNode n, WalkContext c, CAstVisitor<WalkContext> visitor) { WalkContext context = c; c.setValue(n, context.currentScope().getConstantValue(n.getValue())); } @Override protected boolean visitBinaryExpr(CAstNode n, WalkContext c, CAstVisitor<WalkContext> visitor) { WalkContext context = c; int result = context.currentScope().allocateTempValue(); c.setValue(n, result); return false; } private static boolean handleBinaryOpThrow(CAstNode n, CAstNode op, WalkContext context) { boolean mayBeInteger = handlePossibleThrow(n, context); if (mayBeInteger) { // currently, only integer / and % throw exceptions assert op == CAstOperator.OP_DIV || op == CAstOperator.OP_MOD : CAstPrinter.print(n); } return mayBeInteger; } private static boolean handlePossibleThrow(CAstNode n, WalkContext context) { boolean mayThrow = false; Collection<Object> labels = context.getControlFlow().getTargetLabels(n); if (!labels.isEmpty()) { mayThrow = true; context.cfg().addPreNode(n, context.getUnwindState()); for (Object label : labels) { CAstNode target = context.getControlFlow().getTarget(n, label); if (target == CAstControlFlowMap.EXCEPTION_TO_EXIT) context.cfg().addPreEdgeToExit(n, true); else context.cfg().addPreEdge(n, target, true); } } return mayThrow; } @Override protected void leaveBinaryExpr(CAstNode n, WalkContext c, CAstVisitor<WalkContext> visitor) { WalkContext context = c; int result = c.getValue(n); CAstNode l = n.getChild(1); CAstNode r = n.getChild(2); assert c.getValue(r) != -1 : CAstPrinter.print(n); assert c.getValue(l) != -1 : CAstPrinter.print(n); boolean mayBeInteger = handleBinaryOpThrow(n, n.getChild(0), context); int currentInstruction = context.cfg().currentInstruction; context .cfg() .addInstruction( insts.BinaryOpInstruction( currentInstruction, translateBinaryOpcode(n.getChild(0)), false, false, result, c.getValue(l), c.getValue(r), mayBeInteger)); context .cfg() .noteOperands( currentInstruction, context.getSourceMap().getPosition(l), context.getSourceMap().getPosition(r)); if (mayBeInteger) { context.cfg().newBlock(true); } } @Override protected boolean visitUnaryExpr(CAstNode n, WalkContext c, CAstVisitor<WalkContext> visitor) { WalkContext context = c; int result = context.currentScope().allocateTempValue(); c.setValue(n, result); return false; } @Override protected void leaveUnaryExpr(CAstNode n, WalkContext c, CAstVisitor<WalkContext> visitor) { WalkContext context = c; int result = c.getValue(n); CAstNode v = n.getChild(1); int currentInstruction = context.cfg().currentInstruction; context .cfg() .addInstruction( insts.UnaryOpInstruction( currentInstruction, translateUnaryOpcode(n.getChild(0)), result, c.getValue(v))); context.cfg().noteOperands(currentInstruction, context.getSourceMap().getPosition(v)); } @Override protected boolean visitArrayLength(CAstNode n, WalkContext c, CAstVisitor<WalkContext> visitor) { WalkContext context = c; int result = context.currentScope().allocateTempValue(); c.setValue(n, result); return false; } @Override protected void leaveArrayLength(CAstNode n, WalkContext c, CAstVisitor<WalkContext> visitor) { WalkContext context = c; int result = c.getValue(n); CAstNode arrayExpr = n.getChild(0); int arrayValue = c.getValue(arrayExpr); int currentInstruction = context.cfg().currentInstruction; context .cfg() .addInstruction(insts.ArrayLengthInstruction(currentInstruction, result, arrayValue)); context.cfg().noteOperands(currentInstruction, context.getSourceMap().getPosition(arrayExpr)); } @Override protected boolean visitArrayRef(CAstNode n, WalkContext c, CAstVisitor<WalkContext> visitor) { /* empty */ return false; } @Override protected void leaveArrayRef(CAstNode n, WalkContext c, CAstVisitor<WalkContext> visitor) { WalkContext context = c; int arrayValue = c.getValue(n.getChild(0)); int result = context.currentScope().allocateTempValue(); c.setValue(n, result); arrayOpHandler.doArrayRead(context, result, arrayValue, n, gatherArrayDims(c, n)); } @Override protected boolean visitDeclStmt(CAstNode n, WalkContext c, CAstVisitor<WalkContext> visitor) { /* empty */ return false; } // TODO: should we handle exploded declaration nodes here instead? @Override protected void leaveDeclStmt(CAstNode n, WalkContext c, CAstVisitor<WalkContext> visitor) { CAstSymbol s = (CAstSymbol) n.getChild(0).getValue(); String nm = s.name(); CAstType t = s.type(); Scope scope = c.currentScope(); if (n.getChildCount() == 2) { CAstNode v = n.getChild(1); if (scope.contains(nm) && scope.lookup(nm).getDefiningScope() == scope) { assert !s.isFinal(); doLocalWrite(c, nm, makeType(t), c.getValue(v)); } else if (v.getKind() != CAstNode.CONSTANT && v.getKind() != CAstNode.VAR && v.getKind() != CAstNode.THIS && v.getKind() != CAstNode.BLOCK_EXPR) { scope.declare(s, c.getValue(v)); } else { scope.declare(s); doLocalWrite(c, nm, makeType(t), c.getValue(v)); } } else { c.currentScope().declare(s); } } @Override protected boolean visitReturn(CAstNode n, WalkContext c, CAstVisitor<WalkContext> visitor) { /* empty */ return false; } @Override protected void leaveReturn(CAstNode n, WalkContext c, CAstVisitor<WalkContext> visitor) { WalkContext context = c; int currentInstruction = context.cfg().currentInstruction; if (n.getChildCount() > 0) { CAstNode returnExpr = n.getChild(0); context .cfg() .addInstruction( insts.ReturnInstruction(currentInstruction, c.getValue(returnExpr), false)); context .cfg() .noteOperands(currentInstruction, context.getSourceMap().getPosition(returnExpr)); } else { context.cfg().addInstruction(insts.ReturnInstruction(currentInstruction)); } context.cfg().addPreNode(n, context.getUnwindState()); context.cfg().newBlock(false); context.cfg().addPreEdgeToExit(n, false); } @Override protected boolean visitIfgoto(CAstNode n, WalkContext c, CAstVisitor<WalkContext> visitor) { /* empty */ return false; } @Override protected void leaveIfgoto(CAstNode n, WalkContext c, CAstVisitor<WalkContext> visitor) { WalkContext context = c; int currentInstruction = context.cfg().currentInstruction; switch (n.getChildCount()) { case 1: CAstNode arg = n.getChild(0); context .cfg() .addInstruction( insts.ConditionalBranchInstruction( currentInstruction, translateConditionOpcode(CAstOperator.OP_NE), null, c.getValue(arg), context.currentScope().getConstantValue(0), -1)); context.cfg().noteOperands(currentInstruction, context.getSourceMap().getPosition(arg)); break; case 3: CAstNode op = n.getChild(0); CAstNode leftExpr = n.getChild(1); CAstNode rightExpr = n.getChild(2); context .cfg() .addInstruction( insts.ConditionalBranchInstruction( currentInstruction, translateConditionOpcode(op), null, c.getValue(leftExpr), c.getValue(rightExpr), -1)); context .cfg() .noteOperands( currentInstruction, context.getSourceMap().getPosition(leftExpr), context.getSourceMap().getPosition(rightExpr)); break; default: Assertions.UNREACHABLE(); } context.cfg().addPreNode(n, context.getUnwindState()); context.cfg().addPreEdge(n, context.getControlFlow().getTarget(n, Boolean.TRUE), false); context.cfg().newBlock(true); } @Override protected boolean visitGoto(CAstNode n, WalkContext c, CAstVisitor<WalkContext> visitor) { /* empty */ return false; } @Override protected void leaveGoto(CAstNode n, WalkContext c, CAstVisitor<WalkContext> visitor) { WalkContext context = c; if (!context.cfg().isDeadBlock(context.cfg().getCurrentBlock())) { context.cfg().addPreNode(n, context.getUnwindState()); CAstControlFlowMap controlFlowMap = context.getControlFlow(); context.cfg().addPreEdge(n, controlFlowMap.getTarget(n, null), false); context.cfg().addInstruction(insts.GotoInstruction(context.cfg().currentInstruction, -1)); if (controlFlowMap.getTarget(n, null) == null) { assert controlFlowMap.getTarget(n, null) != null : controlFlowMap + " does not map " + n + " (" + context.getSourceMap().getPosition(n) + ')'; } context.cfg().newBlock(false); } } @Override protected boolean visitLabelStmt(CAstNode n, WalkContext c, CAstVisitor<WalkContext> visitor) { WalkContext context = c; if (!context.getControlFlow().getSourceNodes(n).isEmpty()) { context.cfg().newBlock(true); context.cfg().addPreNode(n, context.getUnwindState()); } return false; } @Override protected void leaveLabelStmt(CAstNode n, WalkContext c, CAstVisitor<WalkContext> visitor) { /* empty */ } protected void processIf( CAstNode n, boolean isExpr, WalkContext c, CAstVisitor<WalkContext> visitor) { WalkContext context = c; PreBasicBlock trueB = null, falseB = null; // conditional CAstNode l = n.getChild(0); visitor.visit(l, context, visitor); int currentInstruction = context.cfg().getCurrentInstruction(); context .cfg() .addInstruction( insts.ConditionalBranchInstruction( currentInstruction, translateConditionOpcode(CAstOperator.OP_EQ), null, c.getValue(l), context.currentScope().getConstantValue(0), -1)); context.cfg().noteOperands(currentInstruction, context.getSourceMap().getPosition(l)); PreBasicBlock srcB = context.cfg().getCurrentBlock(); // true clause context.cfg().newBlock(true); CAstNode r = n.getChild(1); visitor.visit(r, context, visitor); if (isExpr) { currentInstruction = context.cfg().getCurrentInstruction(); context .cfg() .addInstruction(new AssignInstruction(currentInstruction, c.getValue(n), c.getValue(r))); context.cfg().noteOperands(currentInstruction, context.getSourceMap().getPosition(r)); } if (n.getChildCount() == 3) { if (!context.cfg().isDeadBlock(context.cfg().getCurrentBlock())) { context.cfg().addInstruction(insts.GotoInstruction(context.cfg().currentInstruction, -1)); trueB = context.cfg().getCurrentBlock(); // false clause context.cfg().newBlock(false); } falseB = context.cfg().getCurrentBlock(); CAstNode f = n.getChild(2); context.cfg().deadBlocks.remove(falseB); visitor.visit(f, context, visitor); if (isExpr) { currentInstruction = context.cfg().currentInstruction; context .cfg() .addInstruction( new AssignInstruction(currentInstruction, c.getValue(n), c.getValue(f))); context.cfg().noteOperands(currentInstruction, context.getSourceMap().getPosition(f)); } } // end context.cfg().newBlock(true); if (n.getChildCount() == 3) { if (trueB != null) context.cfg().addEdge(trueB, context.cfg().getCurrentBlock()); context.cfg().addEdge(srcB, falseB); } else { context.cfg().addEdge(srcB, context.cfg().getCurrentBlock()); } } // Make final to prevent overriding @Override protected final void leaveIfStmtCondition( CAstNode n, WalkContext c, CAstVisitor<WalkContext> visitor) { /* empty */ } @Override protected final void leaveIfStmtTrueClause( CAstNode n, WalkContext c, CAstVisitor<WalkContext> visitor) { /* empty */ } @Override protected final void leaveIfStmt(CAstNode n, WalkContext c, CAstVisitor<WalkContext> visitor) { /* empty */ } @Override protected final void leaveIfExprCondition( CAstNode n, WalkContext c, CAstVisitor<WalkContext> visitor) { /* empty */ } @Override protected final void leaveIfExprTrueClause( CAstNode n, WalkContext c, CAstVisitor<WalkContext> visitor) { /* empty */ } @Override protected final void leaveIfExpr(CAstNode n, WalkContext c, CAstVisitor<WalkContext> visitor) { /* empty */ } @Override protected boolean visitIfStmt(CAstNode n, WalkContext c, CAstVisitor<WalkContext> visitor) { processIf(n, false, c, visitor); return true; } @Override protected boolean visitIfExpr(CAstNode n, WalkContext c, CAstVisitor<WalkContext> visitor) { WalkContext context = c; int result = context.currentScope().allocateTempValue(); c.setValue(n, result); processIf(n, true, c, visitor); return true; } @Override protected boolean visitNew(CAstNode n, WalkContext c, CAstVisitor<WalkContext> visitor) { /* empty */ return false; } @Override protected void leaveNew(CAstNode n, WalkContext c, CAstVisitor<WalkContext> visitor) { WalkContext context = c; int result = context.currentScope().allocateTempValue(); c.setValue(n, result); int[] arguments; if (n.getChildCount() <= 1) { arguments = null; } else { arguments = new int[n.getChildCount() - 1]; for (int i = 1; i < n.getChildCount(); i++) { arguments[i - 1] = c.getValue(n.getChild(i)); } } doNewObject(context, n, result, n.getChild(0).getValue(), arguments); } @Override protected boolean visitObjectLiteral( CAstNode n, WalkContext c, CAstVisitor<WalkContext> visitor) { /* empty */ return false; } @Override protected void leaveObjectLiteralFieldInit( CAstNode n, int i, WalkContext c, CAstVisitor<WalkContext> visitor) { WalkContext context = c; if (n.getChild(i).getKind() == CAstNode.EMPTY) { handleUnspecifiedLiteralKey(); } doFieldWrite( context, c.getValue(n.getChild(0)), n.getChild(i), n, c.getValue(n.getChild(i + 1))); } @Override protected void leaveObjectLiteral(CAstNode n, WalkContext c, CAstVisitor<WalkContext> visitor) { c.setValue(n, c.getValue(n.getChild(0))); } @Override protected boolean visitArrayLiteral(CAstNode n, WalkContext c, CAstVisitor<WalkContext> visitor) { /* empty */ return false; } @Override protected void leaveArrayLiteralObject( CAstNode n, WalkContext c, CAstVisitor<WalkContext> visitor) { c.setValue(n, c.getValue(n.getChild(0))); } @Override protected void leaveArrayLiteralInitElement( CAstNode n, int i, WalkContext c, CAstVisitor<WalkContext> visitor) { WalkContext context = c; arrayOpHandler.doArrayWrite( context, c.getValue(n.getChild(0)), n, new int[] {context.currentScope().getConstantValue(i - 1)}, c.getValue(n.getChild(i))); } @Override protected void leaveArrayLiteral(CAstNode n, WalkContext c, CAstVisitor<WalkContext> visitor) { /* empty */ } @Override protected boolean visitObjectRef(CAstNode n, WalkContext c, CAstVisitor<WalkContext> visitor) { WalkContext context = c; int result = context.currentScope().allocateTempValue(); c.setValue(n, result); return false; } @Override protected void leaveObjectRef(CAstNode n, WalkContext c, CAstVisitor<WalkContext> visitor) { WalkContext context = c; int result = c.getValue(n); CAstNode elt = n.getChild(1); doFieldRead(context, result, c.getValue(n.getChild(0)), elt, n); } @Override public boolean visitAssign(CAstNode n, WalkContext c, CAstVisitor<WalkContext> visitor) { /* empty */ return false; } @Override public void leaveAssign(CAstNode n, WalkContext c, CAstVisitor<WalkContext> visitor) { if (n.getKind() == CAstNode.ASSIGN) { c.setValue(n, c.getValue(n.getChild(1))); } else { c.setValue(n, c.getValue(n.getChild(0))); } } private static int[] gatherArrayDims(WalkContext c, CAstNode n) { int numDims = n.getChildCount() - 2; int[] dims = new int[numDims]; for (int i = 0; i < numDims; i++) dims[i] = c.getValue(n.getChild(i + 2)); return dims; } /* Prereq: a.getKind() == ASSIGN_PRE_OP || a.getKind() == ASSIGN_POST_OP */ protected int processAssignOp(CAstNode v, CAstNode a, int temp, WalkContext c) { WalkContext context = c; int rval = c.getValue(v); CAstNode op = a.getChild(2); int temp2 = context.currentScope().allocateTempValue(); boolean mayBeInteger = handleBinaryOpThrow(a, op, context); int currentInstruction = context.cfg().getCurrentInstruction(); context .cfg() .addInstruction( insts.BinaryOpInstruction( currentInstruction, translateBinaryOpcode(op), false, false, temp2, temp, rval, mayBeInteger)); context .cfg() .noteOperands( currentInstruction, context.getSourceMap().getPosition(a.getChild(0)), context.getSourceMap().getPosition(v)); if (mayBeInteger) { context.cfg().newBlock(true); } return temp2; } @Override protected boolean visitArrayRefAssign( CAstNode n, CAstNode v, CAstNode a, WalkContext c, CAstVisitor<WalkContext> visitor) { /* empty */ return false; } @Override protected void leaveArrayRefAssign( CAstNode n, CAstNode v, CAstNode a, WalkContext c, CAstVisitor<WalkContext> visitor) { WalkContext context = c; int rval = c.getValue(v); c.setValue(n, rval); arrayOpHandler.doArrayWrite(context, c.getValue(n.getChild(0)), n, gatherArrayDims(c, n), rval); } @Override protected boolean visitArrayRefAssignOp( CAstNode n, CAstNode v, CAstNode a, boolean pre, WalkContext c, CAstVisitor<WalkContext> visitor) { /* empty */ return false; } @Override protected void leaveArrayRefAssignOp( CAstNode n, CAstNode v, CAstNode a, boolean pre, WalkContext c, CAstVisitor<WalkContext> visitor) { WalkContext context = c; int temp = context.currentScope().allocateTempValue(); int[] dims = gatherArrayDims(c, n); arrayOpHandler.doArrayRead(context, temp, c.getValue(n.getChild(0)), n, dims); int rval = processAssignOp(v, a, temp, c); c.setValue(n, pre ? rval : temp); arrayOpHandler.doArrayWrite(context, c.getValue(n.getChild(0)), n, dims, rval); } @Override protected boolean visitObjectRefAssign( CAstNode n, CAstNode v, CAstNode a, WalkContext c, CAstVisitor<WalkContext> visitor) { /* empty */ return false; } @Override protected void leaveObjectRefAssign( CAstNode n, CAstNode v, CAstNode a, WalkContext c, CAstVisitor<WalkContext> visitor) { WalkContext context = c; int rval = c.getValue(v); c.setValue(n, rval); doFieldWrite(context, c.getValue(n.getChild(0)), n.getChild(1), n, rval); } @Override protected boolean visitObjectRefAssignOp( CAstNode n, CAstNode v, CAstNode a, boolean pre, WalkContext c, CAstVisitor<WalkContext> visitor) { /* empty */ return false; } @Override protected void leaveObjectRefAssignOp( CAstNode n, CAstNode v, CAstNode a, boolean pre, WalkContext c, CAstVisitor<WalkContext> visitor) { WalkContext context = c; int temp = context.currentScope().allocateTempValue(); doFieldRead(context, temp, c.getValue(n.getChild(0)), n.getChild(1), n); int rval = processAssignOp(v, a, temp, c); c.setValue(n, pre ? rval : temp); doFieldWrite(context, c.getValue(n.getChild(0)), n.getChild(1), n, rval); } @Override protected boolean visitBlockExprAssign( CAstNode n, CAstNode v, CAstNode a, WalkContext c, CAstVisitor<WalkContext> visitor) { /* empty */ return false; } @Override protected void leaveBlockExprAssign( CAstNode n, CAstNode v, CAstNode a, WalkContext c, CAstVisitor<WalkContext> visitor) { c.setValue(n, c.getValue(n.getChild(n.getChildCount() - 1))); } @Override protected boolean visitBlockExprAssignOp( CAstNode n, CAstNode v, CAstNode a, boolean pre, WalkContext c, CAstVisitor<WalkContext> visitor) { /* empty */ return false; } @Override protected void leaveBlockExprAssignOp( CAstNode n, CAstNode v, CAstNode a, boolean pre, WalkContext c, CAstVisitor<WalkContext> visitor) { /* empty */ c.setValue(n, c.getValue(n.getChild(n.getChildCount() - 1))); } @Override protected boolean visitVarAssign( CAstNode n, CAstNode v, CAstNode a, WalkContext c, CAstVisitor<WalkContext> visitor) { /* empty */ return false; } /** assign rval to nm as appropriate, depending on the scope of ls */ protected void assignValue(CAstNode n, WalkContext context, Symbol ls, String nm, int rval) { if (context.currentScope().isGlobal(ls)) doGlobalWrite(context, nm, makeType(ls.type()), rval); else if (context.currentScope().isLexicallyScoped(ls)) { doLexicallyScopedWrite(context, nm, makeType(ls.type()), rval); } else { assert rval != -1 : CAstPrinter.print(n, context.top().getSourceMap()); doLocalWrite(context, nm, makeType(ls.type()), rval); } } @Override protected void leaveVarAssign( CAstNode n, CAstNode v, CAstNode a, WalkContext c, CAstVisitor<WalkContext> visitor) { WalkContext context = c; int rval = c.getValue(v); String nm = (String) n.getChild(0).getValue(); Symbol ls = context.currentScope().lookup(nm); c.setValue(n, rval); assignValue(n, context, ls, nm, rval); } @Override protected boolean visitVarAssignOp( CAstNode n, CAstNode v, CAstNode a, boolean pre, WalkContext c, CAstVisitor<WalkContext> visitor) { /* empty */ return false; } @Override protected void leaveVarAssignOp( CAstNode n, CAstNode v, CAstNode a, boolean pre, WalkContext c, CAstVisitor<WalkContext> visitor) { WalkContext context = c; String nm = (String) n.getChild(0).getValue(); Symbol ls = context.currentScope().lookup(nm); TypeReference type = makeType(ls.type()); int temp; if (context.currentScope().isGlobal(ls)) temp = doGlobalRead(n, context, nm, type); else if (context.currentScope().isLexicallyScoped(ls)) { temp = doLexicallyScopedRead(n, context, nm, type); } else { temp = doLocalRead(context, nm, type); } if (!pre) { int ret = context.currentScope().allocateTempValue(); int currentInstruction = context.cfg().getCurrentInstruction(); context.cfg().addInstruction(new AssignInstruction(currentInstruction, ret, temp)); context .cfg() .noteOperands(currentInstruction, context.getSourceMap().getPosition(n.getChild(0))); c.setValue(n, ret); } int rval = processAssignOp(v, a, temp, c); if (pre) { c.setValue(n, rval); } if (context.currentScope().isGlobal(ls)) { doGlobalWrite(context, nm, type, rval); } else if (context.currentScope().isLexicallyScoped(ls)) { doLexicallyScopedWrite(context, nm, type, rval); } else { doLocalWrite(context, nm, type, rval); } } private static boolean isSimpleSwitch( CAstNode n, WalkContext context, CAstVisitor<WalkContext> visitor) { boolean hasCase = false; CAstControlFlowMap ctrl = context.getControlFlow(); Collection<Object> caseLabels = ctrl.getTargetLabels(n); for (Object x : caseLabels) { if (x == CAstControlFlowMap.SWITCH_DEFAULT) continue; hasCase = true; CAstNode xn = (CAstNode) x; if (xn.getKind() == CAstNode.CONSTANT) { visitor.visit(xn, context, visitor); if (context.getValue(xn) != -1) { if (context.currentScope().isConstant(context.getValue(xn))) { Object val = context.currentScope().getConstantObject(context.getValue(xn)); if (val instanceof Number) { Number num = (Number) val; if (num.intValue() == num.doubleValue()) { continue; } } } } } return false; } return hasCase; } /** * Translates a CAst SWITCH node using an {@link com.ibm.wala.ssa.SSASwitchInstruction} for the * control flow */ private void doSimpleSwitch(CAstNode n, WalkContext context, CAstVisitor<WalkContext> visitor) { CAstControlFlowMap ctrl = context.getControlFlow(); // handle the expression being switched on CAstNode switchValue = n.getChild(0); visitor.visit(switchValue, context, visitor); int v = context.getValue(switchValue); boolean hasExplicitDefault = ctrl.getTarget(n, CAstControlFlowMap.SWITCH_DEFAULT) != null; Collection<Object> caseLabels = ctrl.getTargetLabels(n); int cases = caseLabels.size(); if (hasExplicitDefault) cases--; // As required by SSASwitchInstruction, the array represents cases in pairs (v,t), where v is // the constant value checked in the switch case and t is the target instruction index for that // case int[] casesAndLabels = new int[cases * 2]; // initialize the switch instruction PreBasicBlock switchInstrBlock = context.cfg().getCurrentBlock(); int currentInstruction = context.cfg().getCurrentInstruction(); context .cfg() .addInstruction( insts.SwitchInstruction(currentInstruction, v, currentInstruction + 1, casesAndLabels)); context.cfg().noteOperands(currentInstruction, context.getSourceMap().getPosition(switchValue)); context.cfg().addPreNode(n, context.getUnwindState()); // initialize the dummy default block with a goto instruction to -1 (its target index will get // corrected in a later phase) context.cfg().newBlock(false); context.cfg().addInstruction(insts.GotoInstruction(context.cfg().currentInstruction, -1)); // dummy block that will just transfer control to either the explicit default block (if present) // or the end of the switch PreBasicBlock dummyDefaultBlock = context.cfg().getCurrentBlock(); // make sure the dummy default block is reachable context.cfg().addEdge(switchInstrBlock, dummyDefaultBlock); // translate all the switch cases (including any explicit default case) context.cfg().newBlock(false); CAstNode switchBody = n.getChild(1); visitor.visit(switchBody, context, visitor); context.cfg().newBlock(true); if (!hasExplicitDefault) { // no explicit default, to jump from the dummy default block to after the switch cases context.cfg().addEdge(dummyDefaultBlock, context.cfg().getCurrentBlock()); } // add appropriate control-flow edges for the switch cases, and populate the casesAndLabels // array int cn = 0; for (Object x : caseLabels) { CAstNode target = ctrl.getTarget(n, x); if (x == CAstControlFlowMap.SWITCH_DEFAULT) { // jump to the explicit default block from the dummy default block context.cfg().addEdge(dummyDefaultBlock, context.cfg().getBlock(target)); } else { Number caseLabel = (Number) context.currentScope().getConstantObject(context.getValue((CAstNode) x)); casesAndLabels[2 * cn] = caseLabel.intValue(); casesAndLabels[2 * cn + 1] = context.cfg().getBlock(target).firstIndex; cn++; // ensure that each case block is a successor of the switch instruction context.cfg().addPreEdge(n, target, false); } } } private void doIfConvertSwitch( CAstNode n, WalkContext context, CAstVisitor<WalkContext> visitor) { CAstControlFlowMap ctrl = context.getControlFlow(); context.cfg().addPreNode(n, context.getUnwindState()); CAstNode switchValue = n.getChild(0); visitor.visit(switchValue, context, visitor); int v = context.getValue(switchValue); Collection<Object> caseLabels = ctrl.getTargetLabels(n); Map<Object, PreBasicBlock> labelToBlock = new LinkedHashMap<>(); for (Object x : caseLabels) { if (x != CAstControlFlowMap.SWITCH_DEFAULT) { visitor.visit((CAstNode) x, context, visitor); int currentInstruction = context.cfg().getCurrentInstruction(); context .cfg() .addInstruction( insts.ConditionalBranchInstruction( currentInstruction, translateConditionOpcode(CAstOperator.OP_EQ), null, v, context.getValue((CAstNode) x), -1)); context .cfg() .noteOperands( currentInstruction, context.getSourceMap().getPosition(switchValue), context.getSourceMap().getPosition((CAstNode) x)); labelToBlock.put(x, context.cfg().getCurrentBlock()); context.cfg().newBlock(true); } } PreBasicBlock defaultGotoBlock = context.cfg().getCurrentBlock(); context.cfg().addInstruction(insts.GotoInstruction(context.cfg().currentInstruction, -1)); context.cfg().newBlock(false); CAstNode switchBody = n.getChild(1); visitor.visit(switchBody, context, visitor); context.cfg().newBlock(true); for (Object x : caseLabels) { if (x != CAstControlFlowMap.SWITCH_DEFAULT) { CAstNode target = ctrl.getTarget(n, x); context.cfg().addEdge(labelToBlock.get(x), context.cfg().getBlock(target)); } } if (ctrl.getTarget(n, CAstControlFlowMap.SWITCH_DEFAULT) == null) { context.cfg().addEdge(defaultGotoBlock, context.cfg().getCurrentBlock()); } else { CAstNode target = ctrl.getTarget(n, CAstControlFlowMap.SWITCH_DEFAULT); context.cfg().addEdge(defaultGotoBlock, context.cfg().getBlock(target)); } } @Override protected boolean visitSwitch(CAstNode n, WalkContext c, CAstVisitor<WalkContext> visitor) { WalkContext context = c; if (isSimpleSwitch(n, context, visitor)) { doSimpleSwitch(n, context, visitor); } else { doIfConvertSwitch(n, context, visitor); } return true; } // Make final to prevent overriding @Override protected final void leaveSwitchValue( CAstNode n, WalkContext c, CAstVisitor<WalkContext> visitor) { /* empty */ } @Override protected final void leaveSwitch(CAstNode n, WalkContext c, CAstVisitor<WalkContext> visitor) { /* empty */ } @Override protected boolean visitThrow(CAstNode n, WalkContext c, CAstVisitor<WalkContext> visitor) { /* empty */ return false; } @Override protected void leaveThrow(CAstNode n, WalkContext c, CAstVisitor<WalkContext> visitor) { WalkContext context = c; doThrow(context, c.getValue(n.getChild(0))); context.cfg().addPreNode(n, context.getUnwindState()); context.cfg().newBlock(false); Collection<Object> labels = context.getControlFlow().getTargetLabels(n); for (Object label : labels) { CAstNode target = context.getControlFlow().getTarget(n, label); if (target == CAstControlFlowMap.EXCEPTION_TO_EXIT) context.cfg().addPreEdgeToExit(n, true); else context.cfg().addPreEdge(n, target, true); } } @Override protected boolean visitCatch(CAstNode n, WalkContext c, CAstVisitor<WalkContext> visitor) { WalkContext context = c; // unreachable catch block if (context.getControlFlow().getSourceNodes(n).isEmpty()) { return true; } String id = (String) n.getChild(0).getValue(); context.cfg().setCurrentBlockAsHandler(); /* if (!context.currentScope().contains(id)) { context.currentScope().declare(new FinalCAstSymbol(id, exceptionType())); } */ int v = context.currentScope().allocateTempValue(); context .cfg() .addInstruction( insts.GetCaughtExceptionInstruction( context.cfg().currentInstruction, context.cfg().getCurrentBlock().getNumber(), v)); context.cfg().addPreNode(n, context.getUnwindState()); doLocalWrite(context, id, defaultCatchType(), v); CAstType caughtType = getTypeForNode(context, n); if (caughtType != null) { setType(context, n, caughtType); } else { context.setCatchType(n, defaultCatchType()); } return false; } private void setType(WalkContext context, CAstNode n, CAstType caughtType) { if (caughtType instanceof CAstType.Union) { for (CAstType type : ((CAstType.Union) caughtType).getConstituents()) { setType(context, n, type); } } else { TypeReference caughtRef = makeType(caughtType); context.setCatchType(n, caughtRef); } } @Override protected void leaveCatch(CAstNode n, WalkContext c, CAstVisitor<WalkContext> visitor) { /* empty */ } @Override protected boolean visitUnwind(CAstNode n, WalkContext c, CAstVisitor<WalkContext> visitor) { /* empty */ return false; } @Override protected void leaveUnwind(CAstNode n, WalkContext c, CAstVisitor<WalkContext> visitor) { /* empty */ } private boolean hasIncomingEdges(CAstNode n, WalkContext context) { if (context.cfg().hasDelayedEdges(n)) { return true; } else { for (CAstNode child : n.getChildren()) { if (hasIncomingEdges(child, context)) { return true; } } return false; } } @Override protected boolean visitTry(final CAstNode n, WalkContext c, CAstVisitor<WalkContext> visitor) { final WalkContext context = c; boolean addSkipCatchGoto = false; visitor.visit(n.getChild(0), context, visitor); PreBasicBlock endOfTry = context.cfg().getCurrentBlock(); if (!hasIncomingEdges(n.getChild(1), context)) { if (loader instanceof CAstAbstractLoader) { ((CAstAbstractLoader) loader) .addMessage( context.getModule(), new Warning(Warning.MILD) { @Override public String getMsg() { return "Dead catch block at " + getPosition(context.getSourceMap(), n.getChild(1)); } }); } return true; } if (!context.cfg().isDeadBlock(context.cfg().getCurrentBlock())) { addSkipCatchGoto = true; context.cfg().addInstruction(insts.GotoInstruction(context.cfg().currentInstruction, -1)); context.cfg().newBlock(false); } context.cfg().noteCatchBlock(); visitor.visit(n.getChild(1), context, visitor); if (!context.cfg().isDeadBlock(context.cfg().getCurrentBlock())) { context.cfg().newBlock(true); } if (addSkipCatchGoto) { PreBasicBlock afterBlock = context.cfg().getCurrentBlock(); context.cfg().addEdge(endOfTry, afterBlock); } return true; } // Make final to prevent overriding @Override protected final void leaveTryBlock(CAstNode n, WalkContext c, CAstVisitor<WalkContext> visitor) { /* empty */ } @Override protected final void leaveTry(CAstNode n, WalkContext c, CAstVisitor<WalkContext> visitor) { /* empty */ } @Override protected boolean visitEmpty(CAstNode n, WalkContext c, CAstVisitor<WalkContext> visitor) { /* empty */ return false; } @Override protected void leaveEmpty(CAstNode n, WalkContext c, CAstVisitor<WalkContext> visitor) { WalkContext context = c; c.setValue(n, context.currentScope().getConstantValue(null)); } @Override protected boolean visitPrimitive(CAstNode n, WalkContext c, CAstVisitor<WalkContext> visitor) { /* empty */ return false; } @Override protected void leavePrimitive(CAstNode n, WalkContext c, CAstVisitor<WalkContext> visitor) { WalkContext context = c; int result = context.currentScope().allocateTempValue(); c.setValue(n, result); doPrimitive(result, context, n); } @Override protected boolean visitVoid(CAstNode n, WalkContext c, CAstVisitor<WalkContext> visitor) { /* empty */ return false; } @Override protected void leaveVoid(CAstNode n, WalkContext c, CAstVisitor<WalkContext> visitor) { c.setValue(n, -1); } @Override protected boolean visitAssert(CAstNode n, WalkContext c, CAstVisitor<WalkContext> visitor) { /* empty */ return false; } @Override protected void leaveAssert(CAstNode n, WalkContext c, CAstVisitor<WalkContext> visitor) { WalkContext context = c; boolean fromSpec = true; CAstNode assertion = n.getChild(0); int result = c.getValue(assertion); if (n.getChildCount() == 2) { assert n.getChild(1).getKind() == CAstNode.CONSTANT; assert n.getChild(1).getValue() instanceof Boolean; fromSpec = n.getChild(1).getValue().equals(Boolean.TRUE); } int currentInstruction = context.cfg().currentInstruction; context.cfg().addInstruction(new AstAssertInstruction(currentInstruction, result, fromSpec)); context.cfg().noteOperands(currentInstruction, context.getSourceMap().getPosition(assertion)); } @Override protected boolean visitEachElementGet( CAstNode n, WalkContext c, CAstVisitor<WalkContext> visitor) { return false; } @Override protected void leaveEachElementGet(CAstNode n, WalkContext c, CAstVisitor<WalkContext> visitor) { int result = c.currentScope().allocateTempValue(); c.setValue(n, result); int currentInstruction = c.cfg().getCurrentInstruction(); c.cfg() .unknownInstructions( () -> c.cfg() .addInstruction( new EachElementGetInstruction( currentInstruction, result, c.getValue(n.getChild(0)), c.getValue(n.getChild(1))))); c.cfg() .noteOperands( currentInstruction, c.getSourceMap().getPosition(n.getChild(0)), c.getSourceMap().getPosition(n.getChild(1))); if (handlePossibleThrow(n, c)) { c.cfg().newBlock(true); } } @Override protected boolean visitEachElementHasNext( CAstNode n, WalkContext c, CAstVisitor<WalkContext> visitor) { return false; } @Override protected void leaveEachElementHasNext( CAstNode n, WalkContext c, CAstVisitor<WalkContext> visitor) { int result = c.currentScope().allocateTempValue(); c.setValue(n, result); int currentInstruction = c.cfg().getCurrentInstruction(); c.cfg() .addInstruction( new EachElementHasNextInstruction( currentInstruction, result, c.getValue(n.getChild(0)), c.getValue(n.getChild(1)))); c.cfg() .noteOperands( currentInstruction, c.getSourceMap().getPosition(n.getChild(0)), c.getSourceMap().getPosition(n.getChild(1))); } @Override protected boolean visitTypeLiteralExpr( CAstNode n, WalkContext c, CAstVisitor<WalkContext> visitor) { return false; } @Override protected void leaveTypeLiteralExpr(CAstNode n, WalkContext c, CAstVisitor<WalkContext> visitor) { WalkContext wc = c; assert n.getChild(0).getKind() == CAstNode.CONSTANT; String typeNameStr = (String) n.getChild(0).getValue(); TypeName typeName = TypeName.string2TypeName(typeNameStr); TypeReference typeRef = TypeReference.findOrCreate(loader.getReference(), typeName); int result = wc.currentScope().allocateTempValue(); c.setValue(n, result); wc.cfg() .addInstruction( insts.LoadMetadataInstruction( wc.cfg().currentInstruction, result, loader.getLanguage().getConstantType(typeRef), typeRef)); } @Override protected boolean visitIsDefinedExpr( CAstNode n, WalkContext c, CAstVisitor<WalkContext> visitor) { return false; } @Override protected void leaveIsDefinedExpr(CAstNode n, WalkContext c, CAstVisitor<WalkContext> visitor) { WalkContext wc = c; CAstNode refExpr = n.getChild(0); int ref = c.getValue(refExpr); int result = wc.currentScope().allocateTempValue(); c.setValue(n, result); if (n.getChildCount() == 1) { int currentInstruction = wc.cfg().getCurrentInstruction(); wc.cfg().addInstruction(new AstIsDefinedInstruction(currentInstruction, result, ref)); wc.cfg().noteOperands(currentInstruction, wc.getSourceMap().getPosition(refExpr)); } else { doIsFieldDefined(wc, result, ref, n.getChild(1)); } } @Override protected boolean visitEcho(CAstNode n, WalkContext c, CAstVisitor<WalkContext> visitor) { return false; } @Override protected void leaveEcho(CAstNode n, WalkContext c, CAstVisitor<WalkContext> visitor) { WalkContext wc = c; int rvals[] = new int[n.getChildCount()]; Position rposs[] = new Position[n.getChildCount()]; int i = 0; for (CAstNode child : n.getChildren()) { rvals[i] = c.getValue(child); rposs[i] = c.getSourceMap().getPosition(child); ++i; } int currentInstruction = wc.cfg().getCurrentInstruction(); wc.cfg().addInstruction(new AstEchoInstruction(currentInstruction, rvals)); wc.cfg().noteOperands(currentInstruction, rposs); } @Override protected boolean visitYield(CAstNode n, WalkContext c, CAstVisitor<WalkContext> visitor) { return false; } @Override protected void leaveYield(CAstNode n, WalkContext c, CAstVisitor<WalkContext> visitor) { WalkContext wc = c; int rvals[] = new int[n.getChildCount()]; Position rposs[] = new Position[n.getChildCount()]; int i = 0; for (CAstNode child : n.getChildren()) { rvals[i] = c.getValue(child); rposs[i] = c.getSourceMap().getPosition(child); ++i; } int currentInstruction = wc.cfg().getCurrentInstruction(); wc.cfg().addInstruction(new AstYieldInstruction(currentInstruction, rvals)); wc.cfg().noteOperands(currentInstruction, rposs); } public CAstEntity getIncludedEntity(CAstNode n) { if (n.getChild(0).getKind() == CAstNode.NAMED_ENTITY_REF) { assert namedEntityResolver != null; return namedEntityResolver.get(n.getChild(0).getChild(0).getValue()); } else { return (CAstEntity) n.getChild(0).getValue(); } } @Override protected void leaveInclude(final CAstNode n, WalkContext c, CAstVisitor<WalkContext> visitor) { WalkContext wc = c; CAstEntity included = getIncludedEntity(n); if (included == null) { System.err.println(("cannot find include for " + CAstPrinter.print(n))); System.err.println(("from:\n" + namedEntityResolver)); } else { final boolean isMacroExpansion = (included.getKind() == CAstEntity.MACRO_ENTITY); System.err.println("found " + included.getName() + " for " + CAstPrinter.print(n)); final CAstEntity copy = new CAstCloner(new CAstImpl(), true) { private CAstNode copyIncludeExpr(CAstNode expr) { if (expr.getValue() != null) { return Ast.makeConstant(expr.getValue()); } else if (expr instanceof CAstOperator) { return expr; } else { List<CAstNode> nc = new ArrayList<>(expr.getChildCount()); for (CAstNode child : expr.getChildren()) { nc.add(copyIncludeExpr(child)); } return Ast.makeNode(expr.getKind(), nc); } } @Override protected CAstNode copyNodes( CAstNode root, final CAstControlFlowMap cfg, NonCopyingContext c, Map<Pair<CAstNode, NoKey>, CAstNode> nodeMap) { if (isMacroExpansion && root.getKind() == CAstNode.MACRO_VAR) { int arg = ((Number) root.getChild(0).getValue()).intValue(); CAstNode expr = copyIncludeExpr(n.getChild(arg)); nodeMap.put(Pair.make(root, c.key()), expr); return expr; } else { return super.copyNodes(root, cfg, c, nodeMap); } } }.rewrite(included); if (copy.getAST() == null) { System.err.println((copy.getName() + " has no AST")); } else { visit( copy.getAST(), new DelegatingContext(wc) { @Override public CAstSourcePositionMap getSourceMap() { return copy.getSourceMap(); } @Override public CAstControlFlowMap getControlFlow() { return copy.getControlFlow(); } }, visitor); visitor.visitScopedEntities(copy, copy.getAllScopedEntities(), wc, visitor); } } } protected final void walkEntities(CAstEntity N, WalkContext c) { visitEntities(N, c, this); } public final class RootContext implements WalkContext { private final Scope globalScope; private final CAstEntity N; private final ModuleEntry module; private final Map<CAstEntity, String> entityNames = new LinkedHashMap<>(); public RootContext(CAstEntity N, ModuleEntry module) { this.N = N; this.module = module; this.globalScope = makeGlobalScope(); } @Override public WalkContext codeContext() { assert false; return null; } @Override public ModuleEntry getModule() { return module; } @Override public String file() { return module.getName(); } @Override public CAstEntity top() { return N; } @Override public Scope currentScope() { return globalScope; } @Override public Set<Scope> entityScopes() { return Collections.singleton(globalScope); } @Override public CAstSourcePositionMap getSourceMap() { return N.getSourceMap(); } @Override public CAstControlFlowMap getControlFlow() { return N.getControlFlow(); } @Override public IncipientCFG cfg() { return null; } @Override public UnwindState getUnwindState() { return null; } @Override public String getName() { return null; } @Override public void setCatchType(IBasicBlock<SSAInstruction> bb, TypeReference catchType) {} @Override public void setCatchType(CAstNode castNode, TypeReference catchType) {} @Override public Map<IBasicBlock<SSAInstruction>, TypeReference[]> getCatchTypes() { return null; } @Override public void addEntityName(CAstEntity e, String name) { entityNames.put(e, name); } @Override public String getEntityName(CAstEntity e) { if (e == null) { return null; } else { assert entityNames.containsKey(e); return 'L' + entityNames.get(e); } } @Override public boolean hasValue(CAstNode n) { assert false; return false; } @Override public int setValue(CAstNode n, int v) { assert false; return 0; } @Override public int getValue(CAstNode n) { assert false; return -1; } @Override public Set<Pair<Pair<String, String>, Integer>> exposeNameSet( CAstEntity entity, boolean writeSet) { assert false; return null; } @Override public Set<Access> getAccesses(CAstEntity e) { assert false; return null; } @Override public Scope getGlobalScope() { return globalScope; } } /** translate module, represented by {@link CAstEntity} N */ @Override public void translate(final CAstEntity N, final ModuleEntry module) { translate(N, new RootContext(N, module)); } public void translate(final CAstEntity N, final WalkContext context) { final ExposedNamesCollector exposedNamesCollector = new ExposedNamesCollector(); exposedNamesCollector.run(N); if (liftDeclarationsForLexicalScoping()) { exposedNamesCollector.run(N); } entity2ExposedNames = exposedNamesCollector.getEntity2ExposedNames(); entity2WrittenNames = exposedNamesCollector.getEntity2WrittenNames(); walkEntities(N, context); } protected void doIsFieldDefined(WalkContext context, int result, int ref, CAstNode f) { if (f.getKind() == CAstNode.CONSTANT && f.getValue() instanceof String) { String field = (String) f.getValue(); FieldReference fieldRef = FieldReference.findOrCreate( loader.getLanguage().getRootType(), Atom.findOrCreateUnicodeAtom(field), loader.getLanguage().getRootType()); context .cfg() .addInstruction( ((AstInstructionFactory) insts) .IsDefinedInstruction( context.cfg().getCurrentInstruction(), result, ref, fieldRef)); } else { context .cfg() .addInstruction( ((AstInstructionFactory) insts) .IsDefinedInstruction( context.cfg().getCurrentInstruction(), result, ref, context.getValue(f))); } } }
172,516
30.033819
100
java
WALA
WALA-master/cast/src/main/java/com/ibm/wala/cast/ir/translator/ConstantFoldingRewriter.java
/* * Copyright (c) 2013 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.cast.ir.translator; import com.ibm.wala.cast.tree.CAst; import com.ibm.wala.cast.tree.CAstControlFlowMap; import com.ibm.wala.cast.tree.CAstNode; import com.ibm.wala.cast.tree.impl.CAstOperator; import com.ibm.wala.cast.tree.rewrite.CAstBasicRewriter; import com.ibm.wala.cast.tree.rewrite.CAstBasicRewriter.NonCopyingContext; import com.ibm.wala.util.collections.Pair; import java.util.List; import java.util.Map; public abstract class ConstantFoldingRewriter extends CAstBasicRewriter<NonCopyingContext> { protected ConstantFoldingRewriter(CAst Ast) { super(Ast, new NonCopyingContext(), true); } protected abstract Object eval(CAstOperator op, Object lhs, Object rhs); @Override protected CAstNode copyNodes( CAstNode root, CAstControlFlowMap cfg, NonCopyingContext context, Map<Pair<CAstNode, NoKey>, CAstNode> nodeMap) { CAstNode result; if (root.getKind() == CAstNode.BINARY_EXPR) { CAstNode left = copyNodes(root.getChild(1), cfg, context, nodeMap); CAstNode right = copyNodes(root.getChild(2), cfg, context, nodeMap); Object v; if (left.getKind() == CAstNode.CONSTANT && right.getKind() == CAstNode.CONSTANT && (v = eval((CAstOperator) root.getChild(0), left.getValue(), right.getValue())) != null) { result = Ast.makeConstant(v); } else { result = Ast.makeNode(CAstNode.BINARY_EXPR, root.getChild(0), left, right); } } else if (root.getKind() == CAstNode.IF_EXPR || root.getKind() == CAstNode.IF_STMT) { CAstNode expr = copyNodes(root.getChild(0), cfg, context, nodeMap); if (expr.getKind() == CAstNode.CONSTANT && expr.getValue() == Boolean.TRUE) { result = copyNodes(root.getChild(1), cfg, context, nodeMap); } else if (expr.getKind() == CAstNode.CONSTANT && root.getChildCount() > 2 && expr.getValue() == Boolean.FALSE) { result = copyNodes(root.getChild(2), cfg, context, nodeMap); } else { CAstNode then = copyNodes(root.getChild(1), cfg, context, nodeMap); if (root.getChildCount() == 3) { result = Ast.makeNode( root.getKind(), expr, then, copyNodes(root.getChild(2), cfg, context, nodeMap)); } else { result = Ast.makeNode(root.getKind(), expr, then); } } } else if (root.getKind() == CAstNode.CONSTANT) { result = Ast.makeConstant(root.getValue()); } else if (root.getKind() == CAstNode.OPERATOR) { result = root; } else { List<CAstNode> children = copyChildrenArrayAndTargets(root, cfg, context, nodeMap); CAstNode copy = Ast.makeNode(root.getKind(), children); result = copy; } nodeMap.put(Pair.make(root, context.key()), result); return result; } }
3,211
36.348837
98
java
WALA
WALA-master/cast/src/main/java/com/ibm/wala/cast/ir/translator/ExposedNamesCollector.java
/* * Copyright (c) 2013 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.cast.ir.translator; import com.ibm.wala.cast.tree.CAstEntity; import com.ibm.wala.cast.tree.CAstNode; import com.ibm.wala.cast.tree.CAstSourcePositionMap; import com.ibm.wala.cast.tree.CAstSymbol; import com.ibm.wala.cast.tree.visit.CAstVisitor; import com.ibm.wala.util.collections.HashMapFactory; import com.ibm.wala.util.collections.MapUtil; import com.ibm.wala.util.collections.Pair; import java.util.Map; import java.util.Set; /** * discovers which names declared by an {@link CAstEntity entity} are exposed, i.e., accessed by * nested functions. */ public class ExposedNamesCollector extends CAstVisitor<ExposedNamesCollector.EntityContext> { /** names declared by each entity */ private final Map<CAstEntity, Set<String>> entity2DeclaredNames = HashMapFactory.make(); /** exposed names for each entity, updated as child entities are visited */ private final Map<CAstEntity, Set<String>> entity2ExposedNames = HashMapFactory.make(); /** exposed names for each entity which are written, updated as child entities are visited */ private final Map<CAstEntity, Set<Pair<CAstEntity, String>>> entity2WrittenNames = HashMapFactory.make(); public Map<CAstEntity, Set<String>> getEntity2ExposedNames() { return entity2ExposedNames; } public Map<CAstEntity, Set<Pair<CAstEntity, String>>> getEntity2WrittenNames() { return entity2WrittenNames; } static class EntityContext implements CAstVisitor.Context { private final CAstEntity top; EntityContext(CAstEntity top) { this.top = top; } @Override public CAstEntity top() { return top; } @Override public CAstSourcePositionMap getSourceMap() { return top.getSourceMap(); } } /** * run the collector on an entity * * @param N the entity */ public void run(CAstEntity N) { visitEntities(N, new EntityContext(N), this); } @Override protected EntityContext makeCodeContext(EntityContext context, CAstEntity n) { if (n.getKind() == CAstEntity.FUNCTION_ENTITY) { // need to handle arguments String[] argumentNames = n.getArgumentNames(); for (String arg : argumentNames) { // System.err.println("declaration of " + arg + " in " + n); MapUtil.findOrCreateSet(entity2DeclaredNames, n).add(arg); } } return new EntityContext(n); } @Override protected void leaveDeclStmt(CAstNode n, EntityContext c, CAstVisitor<EntityContext> visitor) { CAstSymbol s = (CAstSymbol) n.getChild(0).getValue(); String nm = s.name(); // System.err.println("declaration of " + nm + " in " + c.top()); MapUtil.findOrCreateSet(entity2DeclaredNames, c.top()).add(nm); } @Override protected void leaveFunctionStmt( CAstNode n, EntityContext c, CAstVisitor<EntityContext> visitor) { CAstEntity fn = (CAstEntity) n.getChild(0).getValue(); String nm = fn.getName(); // System.err.println("declaration of " + nm + " in " + c.top()); MapUtil.findOrCreateSet(entity2DeclaredNames, c.top()).add(nm); } @Override protected void leaveClassStmt(CAstNode n, EntityContext c, CAstVisitor<EntityContext> visitor) { CAstEntity fn = (CAstEntity) n.getChild(0).getValue(); String nm = fn.getName(); // System.err.println("declaration of " + nm + " in " + c.top()); MapUtil.findOrCreateSet(entity2DeclaredNames, c.top()).add(nm); } private void checkForLexicalAccess(Context c, String nm, boolean isWrite) { CAstEntity entity = c.top(); final Set<String> entityNames = entity2DeclaredNames.get(entity); if (entityNames == null || !entityNames.contains(nm)) { CAstEntity declaringEntity = null; CAstEntity curEntity = getParent(entity); while (curEntity != null) { final Set<String> curEntityNames = entity2DeclaredNames.get(curEntity); if (curEntityNames != null && curEntityNames.contains(nm)) { declaringEntity = curEntity; break; } else { curEntity = getParent(curEntity); } } if (declaringEntity != null) { // System.err.println("marking " + nm + " from entity " + declaringEntity + " as exposed"); MapUtil.findOrCreateSet(entity2ExposedNames, declaringEntity).add(nm); if (isWrite) { MapUtil.findOrCreateSet(entity2WrittenNames, declaringEntity).add(Pair.make(entity, nm)); } } } } @Override protected void leaveVar(CAstNode n, EntityContext c, CAstVisitor<EntityContext> visitor) { String nm = (String) n.getChild(0).getValue(); checkForLexicalAccess(c, nm, false); } @Override protected void leaveVarAssignOp( CAstNode n, CAstNode v, CAstNode a, boolean pre, EntityContext c, CAstVisitor<EntityContext> visitor) { checkForLexicalAccess(c, (String) n.getChild(0).getValue(), true); } @Override protected void leaveVarAssign( CAstNode n, CAstNode v, CAstNode a, EntityContext c, CAstVisitor<EntityContext> visitor) { checkForLexicalAccess(c, (String) n.getChild(0).getValue(), true); } @Override protected boolean doVisit(CAstNode n, EntityContext context, CAstVisitor<EntityContext> visitor) { // assume unknown node types don't do anything relevant to exposed names. // override if this is untrue return true; } @Override protected boolean doVisitAssignNodes( CAstNode n, EntityContext context, CAstNode v, CAstNode a, CAstVisitor<EntityContext> visitor) { // assume unknown node types don't do anything relevant to exposed names. // override if this is untrue return true; } }
6,055
32.458564
100
java
WALA
WALA-master/cast/src/main/java/com/ibm/wala/cast/ir/translator/NativeBridge.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.cast.ir.translator; import com.ibm.wala.cast.tree.CAst; /** * superclass for CAst parsers / translators making use of native code. performs initialization of * the core CAst native library. */ public abstract class NativeBridge { protected final CAst Ast; protected NativeBridge(CAst Ast) { this.Ast = Ast; } }
724
25.851852
98
java
WALA
WALA-master/cast/src/main/java/com/ibm/wala/cast/ir/translator/NativeTranslatorToCAst.java
package com.ibm.wala.cast.ir.translator; import com.ibm.wala.cast.tree.CAst; import com.ibm.wala.cast.tree.CAstEntity; import com.ibm.wala.cast.tree.CAstSourcePositionMap.Position; import com.ibm.wala.cast.tree.impl.AbstractSourcePosition; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.net.URL; /** common functionality for any {@link TranslatorToCAst} making use of native code */ public abstract class NativeTranslatorToCAst extends NativeBridge implements TranslatorToCAst { protected final URL sourceURL; protected final String sourceFileName; protected NativeTranslatorToCAst(CAst Ast, URL sourceURL, String sourceFileName) { super(Ast); this.sourceURL = sourceURL; this.sourceFileName = sourceFileName; } protected String getLocalFile() { return sourceFileName; } protected String getFile() { return sourceURL.getFile(); } protected Position makeLocation(final int fl, final int fc, final int ll, final int lc) { return new AbstractSourcePosition() { @Override public int getFirstLine() { return fl; } @Override public int getLastLine() { return ll; } @Override public int getFirstCol() { return fc; } @Override public int getLastCol() { return lc; } @Override public int getFirstOffset() { return -1; } @Override public int getLastOffset() { return -1; } @Override public URL getURL() { return sourceURL; } public InputStream getInputStream() throws IOException { return new FileInputStream(sourceFileName); } @Override public String toString() { String urlString = sourceURL.toString(); if (urlString.lastIndexOf(File.separator) == -1) return "[" + fl + ':' + fc + "]->[" + ll + ':' + lc + ']'; else return urlString.substring(urlString.lastIndexOf(File.separator) + 1) + "@[" + fl + ':' + fc + "]->[" + ll + ':' + lc + ']'; } @Override public Reader getReader() throws IOException { return new InputStreamReader(getInputStream()); } }; } @Override public abstract CAstEntity translateToCAst(); }
2,523
23.038095
95
java
WALA
WALA-master/cast/src/main/java/com/ibm/wala/cast/ir/translator/RewritingTranslatorToCAst.java
package com.ibm.wala.cast.ir.translator; import com.ibm.wala.cast.tree.CAstEntity; import com.ibm.wala.cast.tree.impl.CAstImpl; import com.ibm.wala.cast.tree.rewrite.CAstRewriter.CopyKey; import com.ibm.wala.cast.tree.rewrite.CAstRewriter.RewriteContext; import com.ibm.wala.cast.tree.rewrite.CAstRewriterFactory; import com.ibm.wala.classLoader.ModuleEntry; import java.io.IOException; import java.util.ArrayList; import java.util.List; public class RewritingTranslatorToCAst implements TranslatorToCAst { private final List<CAstRewriterFactory<?, ?>> rewriters = new ArrayList<>(); protected final ModuleEntry M; private final TranslatorToCAst base; public RewritingTranslatorToCAst(ModuleEntry m2, TranslatorToCAst base) { this.M = m2; this.base = base; } @Override public <C extends RewriteContext<K>, K extends CopyKey<K>> void addRewriter( CAstRewriterFactory<C, K> factory, boolean prepend) { if (prepend) rewriters.add(0, factory); else rewriters.add(factory); } @Override public CAstEntity translateToCAst() throws IOException, Error { CAstImpl Ast = new CAstImpl(); CAstEntity entity = base.translateToCAst(); for (CAstRewriterFactory<?, ?> rwf : rewriters) entity = rwf.createCAstRewriter(Ast).rewrite(entity); return entity; } }
1,312
32.666667
78
java
WALA
WALA-master/cast/src/main/java/com/ibm/wala/cast/ir/translator/TranslatorToCAst.java
/* * Copyright (c) 2013 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.cast.ir.translator; import com.ibm.wala.cast.tree.CAst; import com.ibm.wala.cast.tree.CAstEntity; import com.ibm.wala.cast.tree.CAstNode; import com.ibm.wala.cast.tree.CAstSourcePositionMap.Position; import com.ibm.wala.cast.tree.impl.CAstControlFlowRecorder; import com.ibm.wala.cast.tree.impl.CAstNodeTypeMapRecorder; import com.ibm.wala.cast.tree.impl.CAstSourcePositionRecorder; import com.ibm.wala.cast.tree.rewrite.CAstCloner; import com.ibm.wala.cast.tree.rewrite.CAstRewriter; import com.ibm.wala.cast.tree.rewrite.CAstRewriter.CopyKey; import com.ibm.wala.cast.tree.rewrite.CAstRewriter.RewriteContext; import com.ibm.wala.cast.tree.rewrite.CAstRewriterFactory; import com.ibm.wala.core.util.warnings.Warning; import com.ibm.wala.util.WalaException; import com.ibm.wala.util.collections.HashMapFactory; import java.io.IOException; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; public interface TranslatorToCAst { <C extends RewriteContext<K>, K extends CopyKey<K>> void addRewriter( CAstRewriterFactory<C, K> factory, boolean prepend); class Error extends WalaException { private static final long serialVersionUID = -8440950320425119751L; public final Set<Warning> warning; public Error(Set<Warning> message) { super(message.iterator().next().getMsg()); warning = message; } } CAstEntity translateToCAst() throws Error, IOException; interface WalkContext<C extends WalkContext<C, T>, T> { WalkContext<C, T> getParent(); /** * Add a name declaration to this context. For variables or constants, n should be a {@link * CAstNode#DECL_STMT}, and the initialization of the variable (if any) may occur in a separate * assignment. For functions, n should be a {@link CAstNode#FUNCTION_STMT}, including the * function body. */ default void addNameDecl(CAstNode n) { getParent().addNameDecl(n); } default List<CAstNode> getNameDecls() { return getParent().getNameDecls(); } /** * get a mapping from CAstNodes to the scoped entities (e.g. functions or local classes) * introduced by those nodes. Also maps {@code null} to those entities not corresponding to any * node (e.g nested classes) */ default Map<CAstNode, Collection<CAstEntity>> getScopedEntities() { return getParent().getScopedEntities(); } default CAstNode getCatchTarget() { return getParent().getCatchTarget(); } default CAstNode getCatchTarget(String s) { return getParent().getCatchTarget(s); } default T top() { return getParent().top(); } /** associate a child entity with a given CAstNode, e.g. for a function declaration */ default void addScopedEntity(CAstNode newNode, CAstEntity visit) { getParent().addScopedEntity(newNode, visit); } /** for recording control-flow relationships among the CAst nodes */ default CAstControlFlowRecorder cfg() { return getParent().cfg(); } /** for recording source positions */ default CAstSourcePositionRecorder pos() { return getParent().pos(); } /** for recording types of nodes */ default CAstNodeTypeMapRecorder getNodeTypeMap() { return getParent().getNodeTypeMap(); } /** for a 'continue' style goto, return the control flow target */ default T getContinueFor(String label) { return getParent().getContinueFor(label); } /** for a 'break' style goto, return the control flow target */ default T getBreakFor(String label) { return getParent().getBreakFor(label); } } class RootContext<C extends WalkContext<C, T>, T> implements WalkContext<C, T> { @Override public Map<CAstNode, Collection<CAstEntity>> getScopedEntities() { assert false; return Collections.emptyMap(); } @Override public List<CAstNode> getNameDecls() { return null; } @Override public void addScopedEntity(CAstNode newNode, CAstEntity visit) { assert false; } @Override public CAstControlFlowRecorder cfg() { assert false; return null; } @Override public CAstSourcePositionRecorder pos() { assert false; return null; } @Override public CAstNodeTypeMapRecorder getNodeTypeMap() { assert false; return null; } @Override public T getContinueFor(String label) { assert false; return null; } @Override public T getBreakFor(String label) { assert false; return null; } @Override public T top() { assert false; return null; } @Override public WalkContext<C, T> getParent() { assert false; return null; } } class DelegatingContext<C extends WalkContext<C, T>, T> implements WalkContext<C, T> { protected final C parent; protected DelegatingContext(C parent) { this.parent = parent; } @Override public T top() { return parent.top(); } @Override public WalkContext<C, T> getParent() { return parent; } } class BreakContext<C extends WalkContext<C, T>, T> extends DelegatingContext<C, T> { private final T breakTarget; protected final String label; protected BreakContext(C parent, T breakTarget, String label) { super(parent); this.breakTarget = breakTarget; this.label = label; } @Override public T getBreakFor(String l) { return (l == null || l.equals(label)) ? breakTarget : super.getBreakFor(l); } } class LoopContext<C extends WalkContext<C, T>, T> extends BreakContext<C, T> { private final T continueTo; protected LoopContext(C parent, T breakTo, T continueTo, String label) { super(parent, breakTo, label); this.continueTo = continueTo; } @Override public T getContinueFor(String l) { return (l == null || l.equals(label)) ? continueTo : super.getContinueFor(l); } } class TryCatchContext<C extends WalkContext<C, T>, T> implements WalkContext<C, T> { private final Map<String, CAstNode> catchNode; private final WalkContext<C, T> parent; protected TryCatchContext(C parent, CAstNode catchNode) { this(parent, Collections.singletonMap(null, catchNode)); } protected TryCatchContext(C parent, Map<String, CAstNode> catchNode) { this.parent = parent; this.catchNode = catchNode; } @Override public CAstNode getCatchTarget() { return getCatchTarget(null); } @Override public CAstNode getCatchTarget(String s) { return catchNode.get(s); } @Override public WalkContext<C, T> getParent() { return parent; } } class FunctionContext<C extends WalkContext<C, T>, T> extends DelegatingContext<C, T> { private final T topNode; private final CAstSourcePositionRecorder pos = new CAstSourcePositionRecorder(); private final CAstControlFlowRecorder cfg = new CAstControlFlowRecorder(pos); private final Map<CAstNode, Collection<CAstEntity>> scopedEntities = HashMapFactory.make(); protected FunctionContext(C parent, T s) { super(parent); this.topNode = s; } @Override public T top() { return topNode; } @Override public void addScopedEntity(CAstNode construct, CAstEntity e) { if (!scopedEntities.containsKey(construct)) { scopedEntities.put(construct, new HashSet<>(1)); } scopedEntities.get(construct).add(e); } @Override public Map<CAstNode, Collection<CAstEntity>> getScopedEntities() { return scopedEntities; } @Override public CAstControlFlowRecorder cfg() { return cfg; } @Override public CAstSourcePositionRecorder pos() { return pos; } } class DoLoopTranslator { private final boolean replicateForDoLoops; private final CAst Ast; public DoLoopTranslator(boolean replicateForDoLoops, CAst ast) { this.replicateForDoLoops = replicateForDoLoops; Ast = ast; } public CAstNode translateDoLoop( CAstNode loopTest, CAstNode loopBody, CAstNode continueNode, CAstNode breakNode, WalkContext<?, ?> wc) { if (replicateForDoLoops) { loopBody = Ast.makeNode(CAstNode.BLOCK_STMT, loopBody, continueNode); CAstRewriter.Rewrite x = new CAstCloner(Ast, false) .copy(loopBody, wc.cfg(), wc.pos(), wc.getNodeTypeMap(), null, null); CAstNode otherBody = x.newRoot(); wc.cfg().addAll(x.newCfg()); wc.pos().addAll(x.newPos()); wc.getNodeTypeMap().addAll(x.newTypes()); return Ast.makeNode( CAstNode.BLOCK_STMT, loopBody, Ast.makeNode(CAstNode.LOOP, loopTest, otherBody), breakNode); } else { CAstNode header = Ast.makeNode( CAstNode.LABEL_STMT, Ast.makeConstant("_do_label"), Ast.makeNode(CAstNode.EMPTY)); CAstNode loopGoto = Ast.makeNode(CAstNode.IFGOTO, loopTest); wc.cfg().map(header, header); wc.cfg().map(loopGoto, loopGoto); wc.cfg().add(loopGoto, header, Boolean.TRUE); return Ast.makeNode( CAstNode.BLOCK_STMT, header, Ast.makeNode(CAstNode.BLOCK_STMT, loopBody, continueNode), loopGoto, breakNode); } } } default <X extends WalkContext<X, Y>, Y> void pushSourcePosition( WalkContext<X, Y> context, CAstNode n, Position p) { assert context.pos() != null; if (n != null) { if (context.pos().getPosition(n) == null && !(n.getKind() == CAstNode.FUNCTION_EXPR || n.getKind() == CAstNode.FUNCTION_STMT)) { context.pos().setPosition(n, p); for (CAstNode child : n.getChildren()) { pushSourcePosition(context, child, p); } } } } }
10,423
27.40327
99
java
WALA
WALA-master/cast/src/main/java/com/ibm/wala/cast/ir/translator/TranslatorToIR.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.cast.ir.translator; import com.ibm.wala.cast.tree.CAstEntity; import com.ibm.wala.classLoader.ModuleEntry; /** * Type that performs the translation from the CAst to WALA IR (as extended for the language). The * generated IR and related information is stored within the translator. */ public interface TranslatorToIR { /** * translate the CAst rooted at S, corresponding to ModuleEntry N, to IR, and store the result * internally. */ void translate(CAstEntity S, ModuleEntry N); }
895
31
98
java
WALA
WALA-master/cast/src/main/java/com/ibm/wala/cast/loader/AstClass.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.cast.loader; import com.ibm.wala.cast.tree.CAstSourcePositionMap; import com.ibm.wala.classLoader.IClass; import com.ibm.wala.classLoader.IClassLoader; import com.ibm.wala.classLoader.IField; import com.ibm.wala.classLoader.IMethod; import com.ibm.wala.core.util.strings.Atom; import com.ibm.wala.shrike.shrikeCT.ClassConstants; import com.ibm.wala.types.MethodReference; import com.ibm.wala.types.Selector; import com.ibm.wala.types.TypeName; import com.ibm.wala.types.TypeReference; import com.ibm.wala.util.collections.HashSetFactory; import java.io.Reader; import java.net.URL; import java.util.Collection; import java.util.Map; import java.util.Set; public abstract class AstClass implements IClass, ClassConstants { private final CAstSourcePositionMap.Position sourcePosition; private final TypeName typeName; private final TypeReference typeReference; private final IClassLoader loader; private final short modifiers; protected final Map<Atom, IField> declaredFields; protected final Map<Selector, IMethod> declaredMethods; protected AstClass( CAstSourcePositionMap.Position sourcePosition, TypeName typeName, IClassLoader loader, short modifiers, Map<Atom, IField> declaredFields, Map<Selector, IMethod> declaredMethods) { this.sourcePosition = sourcePosition; this.typeName = typeName; this.loader = loader; this.modifiers = modifiers; this.declaredFields = declaredFields; this.declaredMethods = declaredMethods; this.typeReference = TypeReference.findOrCreate(loader.getReference(), typeName); } @Override public boolean isInterface() { return (modifiers & ACC_INTERFACE) != 0; } @Override public boolean isAbstract() { return (modifiers & ACC_ABSTRACT) != 0; } @Override public boolean isPublic() { return (modifiers & ACC_PUBLIC) != 0; } @Override public boolean isPrivate() { return (modifiers & ACC_PRIVATE) != 0; } @Override public boolean isReferenceType() { return true; } @Override public boolean isArrayClass() { return false; } @Override public boolean isSynthetic() { return false; } @Override public int getModifiers() { return modifiers; } public CAstSourcePositionMap.Position getSourcePosition() { return sourcePosition; } public URL getSourceURL() { return sourcePosition.getURL(); } @Override public String getSourceFileName() { return sourcePosition.getURL().getFile(); } @Override public Reader getSource() { return null; } @Override public TypeName getName() { return typeName; } @Override public TypeReference getReference() { return typeReference; } @Override public IClassLoader getClassLoader() { return loader; } @Override public abstract IClass getSuperclass(); private Collection<IClass> gatherInterfaces() { Set<IClass> result = HashSetFactory.make(); result.addAll(getDirectInterfaces()); if (getSuperclass() != null) { result.addAll(getSuperclass().getAllImplementedInterfaces()); } return result; } @Override public abstract Collection<IClass> getDirectInterfaces(); @Override public Collection<IClass> getAllImplementedInterfaces() { return gatherInterfaces(); } @Override public IMethod getClassInitializer() { return getMethod(MethodReference.clinitSelector); } @Override public IMethod getMethod(Selector selector) { if (declaredMethods.containsKey(selector)) { return declaredMethods.get(selector); } else if (getSuperclass() != null) { return getSuperclass().getMethod(selector); } else { return null; } } @Override public IField getField(Atom name) { if (declaredFields.containsKey(name)) { return declaredFields.get(name); } else if (getSuperclass() != null) { return getSuperclass().getField(name); } else { return null; } } @Override public IField getField(Atom name, TypeName type) { // assume that for AST classes, you can't have multiple fields with the same name return getField(name); } @Override public Collection<? extends IMethod> getDeclaredMethods() { return declaredMethods.values(); } @Override public Collection<IField> getDeclaredInstanceFields() { Set<IField> result = HashSetFactory.make(); for (IField F : declaredFields.values()) { if (!F.isStatic()) { result.add(F); } } return result; } @Override public Collection<IField> getDeclaredStaticFields() { Set<IField> result = HashSetFactory.make(); for (IField F : declaredFields.values()) { if (F.isStatic()) { result.add(F); } } return result; } @Override public Collection<IField> getAllInstanceFields() { Collection<IField> result = HashSetFactory.make(); result.addAll(getDeclaredInstanceFields()); if (getSuperclass() != null) { result.addAll(getSuperclass().getAllInstanceFields()); } return result; } @Override public Collection<IField> getAllStaticFields() { Collection<IField> result = HashSetFactory.make(); result.addAll(getDeclaredStaticFields()); if (getSuperclass() != null) { result.addAll(getSuperclass().getAllStaticFields()); } return result; } @Override public Collection<IField> getAllFields() { Collection<IField> result = HashSetFactory.make(); result.addAll(getAllInstanceFields()); result.addAll(getAllStaticFields()); return result; } @Override public Collection<? extends IMethod> getAllMethods() { Collection<IMethod> result = HashSetFactory.make(); result.addAll(getDeclaredMethods()); if (getSuperclass() != null) { result.addAll(getSuperclass().getAllMethods()); } return result; } }
6,265
23.286822
85
java
WALA
WALA-master/cast/src/main/java/com/ibm/wala/cast/loader/AstDynamicField.java
package com.ibm.wala.cast.loader; import com.ibm.wala.classLoader.IClass; import com.ibm.wala.classLoader.IField; import com.ibm.wala.core.util.strings.Atom; import com.ibm.wala.ipa.cha.IClassHierarchy; import com.ibm.wala.types.FieldReference; import com.ibm.wala.types.TypeReference; import com.ibm.wala.types.annotations.Annotation; import java.util.Collection; import java.util.Collections; public class AstDynamicField implements IField { private final boolean isStatic; private final TypeReference descriptor; private final IClass cls; private final Atom name; public AstDynamicField(boolean isStatic, IClass cls, Atom name, TypeReference descriptor) { this.isStatic = isStatic; this.descriptor = descriptor; this.cls = cls; this.name = name; } @Override public String toString() { return "<field " + name + '>'; } @Override public IClass getDeclaringClass() { return cls; } @Override public Atom getName() { return name; } @Override public TypeReference getFieldTypeReference() { return descriptor; } @Override public FieldReference getReference() { return FieldReference.findOrCreate(cls.getReference(), name, descriptor); } @Override public boolean isFinal() { return false; } @Override public boolean isPrivate() { return false; } @Override public boolean isProtected() { return false; } @Override public boolean isPublic() { return false; } @Override public boolean isVolatile() { return false; } @Override public boolean isStatic() { return isStatic; } @Override public IClassHierarchy getClassHierarchy() { return cls.getClassHierarchy(); } @Override public Collection<Annotation> getAnnotations() { return Collections.emptySet(); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((cls == null) ? 0 : cls.hashCode()); result = prime * result + ((descriptor == null) ? 0 : descriptor.hashCode()); result = prime * result + (isStatic ? 1231 : 1237); result = prime * result + ((name == null) ? 0 : name.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; AstDynamicField other = (AstDynamicField) obj; if (cls == null) { if (other.cls != null) return false; } else if (!cls.equals(other.cls)) return false; if (descriptor == null) { if (other.descriptor != null) return false; } else if (!descriptor.equals(other.descriptor)) return false; if (isStatic != other.isStatic) return false; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true; } }
2,889
22.884298
93
java
WALA
WALA-master/cast/src/main/java/com/ibm/wala/cast/loader/AstDynamicPropertyClass.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.cast.loader; import com.ibm.wala.cast.tree.CAstSourcePositionMap; import com.ibm.wala.classLoader.IClassLoader; import com.ibm.wala.classLoader.IField; import com.ibm.wala.classLoader.IMethod; import com.ibm.wala.core.util.strings.Atom; import com.ibm.wala.types.Selector; import com.ibm.wala.types.TypeName; import com.ibm.wala.types.TypeReference; import java.util.HashMap; import java.util.Map; public abstract class AstDynamicPropertyClass extends AstClass { private final TypeReference defaultDescriptor; protected AstDynamicPropertyClass( CAstSourcePositionMap.Position sourcePosition, TypeName typeName, IClassLoader loader, short modifiers, Map<Selector, IMethod> declaredMethods, TypeReference defaultDescriptor) { super(sourcePosition, typeName, loader, modifiers, new HashMap<>(), declaredMethods); this.defaultDescriptor = defaultDescriptor; } @Override public IField getField(final Atom name) { IField x; if (declaredFields.containsKey(name)) { return declaredFields.get(name); } else if (getSuperclass() != null && (x = getSuperclass().getField(name)) != null) { return x; } else { final boolean isStatic = isStaticField(name); declaredFields.put(name, new AstDynamicField(isStatic, this, name, defaultDescriptor)); return declaredFields.get(name); } } protected boolean isStaticField(Atom name) { return name.toString().startsWith("global "); } }
1,878
31.964912
93
java
WALA
WALA-master/cast/src/main/java/com/ibm/wala/cast/loader/AstField.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.cast.loader; import com.ibm.wala.cast.tree.CAstQualifier; import com.ibm.wala.classLoader.IClass; import com.ibm.wala.classLoader.IField; import com.ibm.wala.core.util.strings.Atom; import com.ibm.wala.ipa.cha.IClassHierarchy; import com.ibm.wala.types.FieldReference; import com.ibm.wala.types.TypeReference; import com.ibm.wala.types.annotations.Annotation; import java.util.Collection; public class AstField implements IField { private final Collection<CAstQualifier> qualifiers; private final FieldReference ref; private final IClass declaringClass; private final IClassHierarchy cha; private final Collection<Annotation> annotations; public AstField( FieldReference ref, Collection<CAstQualifier> qualifiers, IClass declaringClass, IClassHierarchy cha, Collection<Annotation> annotations) { this.declaringClass = declaringClass; this.qualifiers = qualifiers; this.ref = ref; this.cha = cha; this.annotations = annotations; } @Override public Collection<Annotation> getAnnotations() { return annotations; } @Override public IClass getDeclaringClass() { return declaringClass; } @Override public String toString() { return "field " + ref.getName(); } @Override public Atom getName() { return ref.getName(); } @Override public TypeReference getFieldTypeReference() { return ref.getFieldType(); } @Override public FieldReference getReference() { return ref; } @Override public boolean isStatic() { return qualifiers.contains(CAstQualifier.STATIC); } @Override public boolean isFinal() { return qualifiers.contains(CAstQualifier.CONST) || qualifiers.contains(CAstQualifier.FINAL); } @Override public boolean isPrivate() { return qualifiers.contains(CAstQualifier.PRIVATE); } @Override public boolean isProtected() { return qualifiers.contains(CAstQualifier.PROTECTED); } @Override public boolean isPublic() { return qualifiers.contains(CAstQualifier.PUBLIC); } @Override public boolean isVolatile() { return qualifiers.contains(CAstQualifier.VOLATILE); } @Override public IClassHierarchy getClassHierarchy() { return cha; } }
2,632
23.37963
96
java
WALA
WALA-master/cast/src/main/java/com/ibm/wala/cast/loader/AstFunctionClass.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.cast.loader; import com.ibm.wala.cast.tree.CAstSourcePositionMap; import com.ibm.wala.cast.types.AstMethodReference; import com.ibm.wala.cast.types.AstTypeReference; import com.ibm.wala.classLoader.IClass; import com.ibm.wala.classLoader.IClassLoader; import com.ibm.wala.classLoader.IField; import com.ibm.wala.classLoader.IMethod; import com.ibm.wala.core.util.strings.Atom; import com.ibm.wala.shrike.shrikeCT.ClassConstants; import com.ibm.wala.types.Selector; import com.ibm.wala.types.TypeName; import com.ibm.wala.types.TypeReference; import java.io.Reader; import java.net.URL; import java.util.Collection; import java.util.Collections; public abstract class AstFunctionClass implements IClass, ClassConstants { private final IClassLoader loader; protected AstMethod functionBody; private final CAstSourcePositionMap.Position sourcePosition; private final TypeReference reference; private final TypeReference superReference; protected AstFunctionClass( TypeReference reference, TypeReference superReference, IClassLoader loader, CAstSourcePositionMap.Position sourcePosition) { this.superReference = superReference; this.sourcePosition = sourcePosition; this.reference = reference; this.loader = loader; } protected AstFunctionClass( TypeReference reference, IClassLoader loader, CAstSourcePositionMap.Position sourcePosition) { this( reference, TypeReference.findOrCreate(reference.getClassLoader(), AstTypeReference.functionTypeName), loader, sourcePosition); } @Override public String toString() { try { return "function " + functionBody.getReference().getDeclaringClass().getName(); } catch (NullPointerException e) { return "<need to set code body>"; } } @Override public IClassLoader getClassLoader() { return loader; } @Override public boolean isInterface() { return false; } @Override public boolean isAbstract() { return functionBody == null; } @Override public boolean isPublic() { return true; } @Override public boolean isPrivate() { return false; } public boolean isStatic() { return false; } @Override public boolean isSynthetic() { return false; } @Override public int getModifiers() { return ACC_PUBLIC; } @Override public IClass getSuperclass() { return loader.lookupClass(superReference.getName()); } @Override public Collection<IClass> getDirectInterfaces() { return Collections.emptySet(); } @Override public Collection<IClass> getAllImplementedInterfaces() { return Collections.emptySet(); } public Collection<IClass> getAllAncestorInterfaces() { return Collections.emptySet(); } @Override public IMethod getMethod(Selector selector) { if (selector.equals(AstMethodReference.fnSelector)) { return functionBody; } else { return loader.lookupClass(superReference.getName()).getMethod(selector); } } @Override public IField getField(Atom name) { return loader.lookupClass(superReference.getName()).getField(name); } @Override public IField getField(Atom name, TypeName type) { // assume that for AST classes, you can't have multiple fields with the same name return loader.lookupClass(superReference.getName()).getField(name); } @Override public TypeReference getReference() { return reference; } public CAstSourcePositionMap.Position getSourcePosition() { return sourcePosition; } public URL getSourceURL() { return sourcePosition.getURL(); } @Override public String getSourceFileName() { return sourcePosition.getURL().getFile(); } @Override public Reader getSource() { return null; } @Override public IMethod getClassInitializer() { return null; } @Override public boolean isArrayClass() { return false; } @Override public Collection<IMethod> getDeclaredMethods() { if (functionBody != null) { return Collections.singleton(functionBody); } else { return Collections.emptySet(); // throw new Error("function " + reference + " has no body!"); } } @Override public Collection<IField> getDeclaredInstanceFields() { return Collections.emptySet(); } @Override public Collection<IField> getDeclaredStaticFields() { return Collections.emptySet(); } @Override public Collection<IField> getAllInstanceFields() { return Collections.emptySet(); } @Override public Collection<IField> getAllStaticFields() { return Collections.emptySet(); } @Override public Collection<IField> getAllFields() { return Collections.emptySet(); } @Override public Collection<IMethod> getAllMethods() { return Collections.singleton(functionBody); } @Override public TypeName getName() { return reference.getName(); } @Override public boolean isReferenceType() { return true; } public AstMethod getCodeBody() { return functionBody; } }
5,457
22.127119
100
java
WALA
WALA-master/cast/src/main/java/com/ibm/wala/cast/loader/AstMethod.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.cast.loader; import com.ibm.wala.cast.ir.translator.AstTranslator; import com.ibm.wala.cast.ir.translator.AstTranslator.AstLexicalInformation; import com.ibm.wala.cast.tree.CAstEntity; import com.ibm.wala.cast.tree.CAstQualifier; import com.ibm.wala.cast.tree.CAstSourcePositionMap.Position; import com.ibm.wala.cfg.AbstractCFG; import com.ibm.wala.cfg.ControlFlowGraph; import com.ibm.wala.cfg.IBasicBlock; import com.ibm.wala.classLoader.IClass; import com.ibm.wala.classLoader.IMethod; import com.ibm.wala.core.util.strings.Atom; import com.ibm.wala.shrike.shrikeCT.InvalidClassFileException; import com.ibm.wala.ssa.SSAInstruction; import com.ibm.wala.ssa.SymbolTable; import com.ibm.wala.types.Descriptor; import com.ibm.wala.types.MethodReference; import com.ibm.wala.types.Selector; import com.ibm.wala.types.TypeReference; import com.ibm.wala.types.annotations.Annotation; import com.ibm.wala.util.collections.Pair; import com.ibm.wala.util.intset.IntSet; import java.io.IOException; import java.util.Collection; import java.util.Map; public abstract class AstMethod implements IMethod { public interface Retranslatable { void retranslate(AstTranslator xlator); CAstEntity getEntity(); } public interface DebuggingInformation { Position getCodeBodyPosition(); Position getCodeNamePosition(); Position getInstructionPosition(int instructionOffset); String[][] getSourceNamesForValues(); Position getOperandPosition(int instructionOffset, int operand); Position getParameterPosition(int param); String getLeadingComment(int instructionOffset) throws IOException; String getFollowingComment(int instructionOffset) throws IOException; } /** * lexical access information for some entity scope. used during call graph construction to handle * lexical accesses. */ public interface LexicalInformation { /** * names possibly accessed in a nested lexical scope, represented as pairs * (name,nameOfDefiningEntity) */ Pair<String, String>[] getExposedNames(); /** * maps each exposed name (via its index in {@link #getExposedNames()}) to its value number at * method exit. */ int[] getExitExposedUses(); /** * get a map from exposed name (via its index in {@link #getExposedNames()}) to its value number * at the instruction at offset instructionOffset. */ int[] getExposedUses(int instructionOffset); /** * return all value numbers appearing as entries in either {@link #getExposedUses(int)} or * {@link #getExitExposedUses()} */ IntSet getAllExposedUses(); /** * return the names of the enclosing methods declaring names that are lexically accessed by the * entity */ String[] getScopingParents(); /** returns true if name may be read in nested lexical scopes but cannot be written */ boolean isReadOnly(String name); /** get the name of this entity, as it appears in the definer portion of a lexical name */ String getScopingName(); } protected final IClass cls; private final Collection<CAstQualifier> qualifiers; private final AbstractCFG<?, ?> cfg; private final SymbolTable symtab; private final MethodReference ref; private final boolean hasCatchBlock; private final boolean hasMonitorOp; private final Map<IBasicBlock<SSAInstruction>, TypeReference[]> catchTypes; private final AstLexicalInformation lexicalInfo; private final DebuggingInformation debugInfo; private final Collection<Annotation> annotations; protected AstMethod( IClass cls, Collection<CAstQualifier> qualifiers, AbstractCFG<?, ?> cfg, SymbolTable symtab, MethodReference ref, boolean hasCatchBlock, Map<IBasicBlock<SSAInstruction>, TypeReference[]> caughtTypes, boolean hasMonitorOp, AstLexicalInformation lexicalInfo, DebuggingInformation debugInfo, Collection<Annotation> annotations) { this.cls = cls; this.cfg = cfg; this.ref = ref; this.symtab = symtab; this.qualifiers = qualifiers; this.catchTypes = caughtTypes; this.hasCatchBlock = hasCatchBlock; this.hasMonitorOp = hasMonitorOp; this.lexicalInfo = lexicalInfo; this.debugInfo = debugInfo; this.annotations = annotations; } protected AstMethod( IClass cls, Collection<CAstQualifier> qualifiers, MethodReference ref, Collection<Annotation> annotations) { this.cls = cls; this.qualifiers = qualifiers; this.ref = ref; this.annotations = annotations; this.cfg = null; this.symtab = null; this.catchTypes = null; this.hasCatchBlock = false; this.hasMonitorOp = false; this.lexicalInfo = null; this.debugInfo = null; assert isAbstract(); } public AbstractCFG<?, ?> cfg() { return cfg; } public SymbolTable symbolTable() { return symtab; } public Map<IBasicBlock<SSAInstruction>, TypeReference[]> catchTypes() { return catchTypes; } public LexicalInformation cloneLexicalInfo() { return new AstLexicalInformation(lexicalInfo); } public LexicalInformation lexicalInfo() { return lexicalInfo; } public DebuggingInformation debugInfo() { return debugInfo; } @Override public Collection<Annotation> getAnnotations() { return annotations; } /** * Parents of this method with respect to lexical scoping, that is, methods containing state * possibly referenced lexically in this method */ public abstract static class LexicalParent { public abstract String getName(); public abstract AstMethod getMethod(); @Override public int hashCode() { return getName().hashCode() * getMethod().hashCode(); } @Override public boolean equals(Object o) { return (o instanceof LexicalParent) && getName().equals(((LexicalParent) o).getName()) && getMethod().equals(((LexicalParent) o).getMethod()); } } public abstract LexicalParent[] getParents(); @Override public IClass getDeclaringClass() { return cls; } @Override public String getSignature() { return ref.getSignature(); } @Override public Selector getSelector() { return ref.getSelector(); } @Override public boolean isClinit() { return getSelector().equals(MethodReference.clinitSelector); } @Override public boolean isInit() { return getSelector().getName().equals(MethodReference.initAtom); } @Override public Atom getName() { return ref.getName(); } @Override public Descriptor getDescriptor() { return ref.getDescriptor(); } @Override public MethodReference getReference() { return ref; } @Override public TypeReference getReturnType() { return ref.getReturnType(); } @Override public boolean isStatic() { return qualifiers.contains(CAstQualifier.STATIC); } @Override public boolean isSynchronized() { return qualifiers.contains(CAstQualifier.SYNCHRONIZED); } @Override public boolean isNative() { return qualifiers.contains(CAstQualifier.NATIVE); } @Override public boolean isWalaSynthetic() { return false; } @Override public boolean isSynthetic() { return false; } @Override public boolean isAbstract() { return qualifiers.contains(CAstQualifier.ABSTRACT); } @Override public boolean isPrivate() { return qualifiers.contains(CAstQualifier.PRIVATE); } @Override public boolean isProtected() { return qualifiers.contains(CAstQualifier.PROTECTED); } @Override public boolean isAnnotation() { return qualifiers.contains(CAstQualifier.ANNOTATION); } @Override public boolean isEnum() { return qualifiers.contains(CAstQualifier.ENUM); } @Override public boolean isModule() { return qualifiers.contains(CAstQualifier.MODULE); } @Override public boolean isPublic() { return qualifiers.contains(CAstQualifier.PUBLIC); } @Override public boolean isFinal() { return qualifiers.contains(CAstQualifier.FINAL); } @Override public boolean isBridge() { return qualifiers.contains(CAstQualifier.VOLATILE); } public ControlFlowGraph<?, ?> getControlFlowGraph() { return cfg; } @Override public boolean hasExceptionHandler() { return hasCatchBlock; } public boolean hasMonitorOp() { return hasMonitorOp; } @Override public int getNumberOfParameters() { return symtab.getParameterValueNumbers().length; } /* BEGIN Custom change: precise bytecode positions */ @Override public SourcePosition getParameterSourcePosition(int paramNum) throws InvalidClassFileException { return null; } /* END Custom change: precise bytecode positions */ @Override public int getLineNumber(int instructionIndex) { Position pos = debugInfo.getInstructionPosition(instructionIndex); if (pos == null) { return -1; } else { return pos.getFirstLine(); } } public Position getSourcePosition() { return debugInfo.getCodeBodyPosition(); } public Position getParameterPosition(int paramIndex) { return debugInfo.getParameterPosition(paramIndex); } @Override public Position getSourcePosition(int instructionIndex) { return debugInfo.getInstructionPosition(instructionIndex); } }
9,750
24.593176
100
java
WALA
WALA-master/cast/src/main/java/com/ibm/wala/cast/loader/CAstAbstractLoader.java
/* * Copyright (c) 2013 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.cast.loader; import com.ibm.wala.cast.tree.CAstSourcePositionMap.Position; import com.ibm.wala.classLoader.IClass; import com.ibm.wala.classLoader.IClassLoader; import com.ibm.wala.classLoader.IMethod; import com.ibm.wala.classLoader.ModuleEntry; import com.ibm.wala.core.util.strings.Atom; import com.ibm.wala.core.util.warnings.Warning; import com.ibm.wala.ipa.cha.IClassHierarchy; import com.ibm.wala.types.TypeName; import com.ibm.wala.util.collections.HashMapFactory; import com.ibm.wala.util.collections.HashSetFactory; import java.io.IOException; import java.io.Reader; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; /** basic abstract class loader implementation */ public abstract class CAstAbstractLoader implements IClassLoader { /** types loaded by this */ protected final Map<TypeName, IClass> types = HashMapFactory.make(); protected final IClassHierarchy cha; protected final IClassLoader parent; /** warnings generated while loading each module */ private final Map<ModuleEntry, Set<Warning>> errors = new HashMap<>(); public CAstAbstractLoader(IClassHierarchy cha, IClassLoader parent) { this.cha = cha; this.parent = parent; } public CAstAbstractLoader(IClassHierarchy cha) { this(cha, null); } private Set<Warning> messagesFor(ModuleEntry module) { if (!errors.containsKey(module)) { errors.put(module, HashSetFactory.make()); } return errors.get(module); } public void addMessages(ModuleEntry module, Set<Warning> message) { messagesFor(module).addAll(message); } public void addMessage(ModuleEntry module, Warning message) { messagesFor(module).add(message); } private Iterator<ModuleEntry> getMessages(final byte severity) { return errors.entrySet().stream() .filter(entry -> entry.getValue().stream().anyMatch(w -> w.getLevel() == severity)) .map(Map.Entry::getKey) .iterator(); } public Iterator<ModuleEntry> getModulesWithParseErrors() { return getMessages(Warning.SEVERE); } public Iterator<ModuleEntry> getModulesWithWarnings() { return getMessages(Warning.MILD); } public Set<Warning> getMessages(ModuleEntry m) { return errors.get(m); } public void clearMessages() { errors.clear(); } public IClass lookupClass(String className, IClassHierarchy cha) { assert this.cha == cha; return types.get(TypeName.string2TypeName(className)); } @Override public IClass lookupClass(TypeName className) { return types.get(className); } @Override public Iterator<IClass> iterateAllClasses() { return types.values().iterator(); } @Override public int getNumberOfClasses() { return types.size(); } @Override public Atom getName() { return getReference().getName(); } @Override public int getNumberOfMethods() { return types.values().stream().mapToInt(cls -> cls.getDeclaredMethods().size()).sum(); } @Override public String getSourceFileName(IMethod method, int bcOffset) { if (!(method instanceof AstMethod)) { return null; } Position pos = ((AstMethod) method).getSourcePosition(bcOffset); if (null == pos) { return null; } return pos.getURL().getFile(); } @Override public String getSourceFileName(IClass klass) { return ((AstClass) klass).getSourcePosition().getURL().getFile(); } @Override public Reader getSource(IClass klass) { try { return ((AstClass) klass).getSourcePosition().getReader(); } catch (IOException e) { return null; } } @Override public Reader getSource(IMethod method, int bcOffset) { try { return ((AstMethod) method).getSourcePosition(bcOffset).getReader(); } catch (IOException e) { return null; } } @Override public IClassLoader getParent() { assert parent != null; return parent; } @Override public void removeAll(Collection<IClass> toRemove) { for (IClass remove : toRemove) { types.remove(remove.getName()); } } }
4,495
25.447059
91
java
WALA
WALA-master/cast/src/main/java/com/ibm/wala/cast/loader/CAstAbstractModuleLoader.java
/* * Copyright (c) 2009 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.cast.loader; import com.ibm.wala.cast.ir.translator.AstTranslator; import com.ibm.wala.cast.ir.translator.AstTranslator.AstLexicalInformation; import com.ibm.wala.cast.ir.translator.AstTranslator.WalkContext; import com.ibm.wala.cast.ir.translator.TranslatorToCAst; import com.ibm.wala.cast.ir.translator.TranslatorToIR; import com.ibm.wala.cast.loader.AstMethod.Retranslatable; import com.ibm.wala.cast.tree.CAst; import com.ibm.wala.cast.tree.CAstEntity; import com.ibm.wala.cast.tree.CAstQualifier; import com.ibm.wala.cast.tree.CAstSourcePositionMap; import com.ibm.wala.cast.tree.impl.CAstImpl; import com.ibm.wala.cast.types.AstMethodReference; import com.ibm.wala.cast.util.CAstPrinter; import com.ibm.wala.cfg.AbstractCFG; import com.ibm.wala.cfg.IBasicBlock; import com.ibm.wala.classLoader.IClass; import com.ibm.wala.classLoader.IClassLoader; import com.ibm.wala.classLoader.IMethod; import com.ibm.wala.classLoader.Module; import com.ibm.wala.classLoader.ModuleEntry; import com.ibm.wala.classLoader.SourceFileModule; import com.ibm.wala.classLoader.SourceModule; import com.ibm.wala.core.util.warnings.Warning; import com.ibm.wala.ipa.cha.IClassHierarchy; import com.ibm.wala.ssa.SSAInstruction; import com.ibm.wala.ssa.SymbolTable; import com.ibm.wala.types.TypeName; import com.ibm.wala.types.TypeReference; import com.ibm.wala.types.annotations.Annotation; import com.ibm.wala.util.collections.Iterator2Iterable; import com.ibm.wala.util.collections.Pair; import com.ibm.wala.util.debug.Assertions; import com.ibm.wala.util.io.TemporaryFile; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.PrintStream; import java.io.PrintWriter; import java.util.Collection; import java.util.Collections; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; /** * abstract class loader that performs CAst and IR generation for relevant entities in a list of * {@link Module}s. Subclasses provide the CAst / IR translators appropriate for the language. */ public abstract class CAstAbstractModuleLoader extends CAstAbstractLoader { private static final boolean DEBUG = false; public CAstAbstractModuleLoader(IClassHierarchy cha, IClassLoader parent) { super(cha, parent); } public CAstAbstractModuleLoader(IClassHierarchy cha) { this(cha, null); } /** * create the appropriate CAst translator for the language and source module * * @param modules all modules in the analysis */ protected abstract TranslatorToCAst getTranslatorToCAst( CAst ast, ModuleEntry M, List<Module> modules) throws IOException; /** should IR be generated for entity? */ protected abstract boolean shouldTranslate(CAstEntity entity); /** * create the appropriate IR translator for the language * * @param topLevelEntities the set of all modules being translated */ protected abstract TranslatorToIR initTranslator( Set<Pair<CAstEntity, ModuleEntry>> topLevelEntities); protected File getLocalFile(SourceModule M) throws IOException { if (M instanceof SourceFileModule) { return ((SourceFileModule) M).getFile(); } else { File f = File.createTempFile("module", ".txt"); f.deleteOnExit(); try (InputStream inputStream = M.getInputStream()) { TemporaryFile.streamToFile(f, inputStream); } return f; } } /** * subclasses should override to perform actions after CAst and IR have been generated. by * default, do nothing */ protected void finishTranslation() {} @Override public void init(final List<Module> modules) { final CAst ast = new CAstImpl(); // convert everything to CAst final Set<Pair<CAstEntity, ModuleEntry>> topLevelEntities = new LinkedHashSet<>(); for (Module module : modules) { translateModuleToCAst(module, ast, topLevelEntities, modules); } // generate IR as needed final TranslatorToIR xlatorToIR = initTranslator(topLevelEntities); for (Pair<CAstEntity, ModuleEntry> p : topLevelEntities) { if (shouldTranslate(p.fst)) { xlatorToIR.translate(p.fst, p.snd); } } if (DEBUG) { for (Map.Entry<TypeName, IClass> entry : types.entrySet()) { try { final IClass value = entry.getValue(); System.err.println( ("found type " + entry.getKey() + " : " + value + " < " + value.getSuperclass())); } catch (Exception e) { System.err.println(e); } } } finishTranslation(); } /** * translate moduleEntry to CAst and store result in topLevelEntities * * @param modules all mofules in the analysis */ private void translateModuleEntryToCAst( ModuleEntry moduleEntry, CAst ast, Set<Pair<CAstEntity, ModuleEntry>> topLevelEntities, List<Module> modules) { try { if (moduleEntry.isModuleFile()) { // nested module translateModuleToCAst(moduleEntry.asModule(), ast, topLevelEntities, modules); } else { TranslatorToCAst xlatorToCAst = getTranslatorToCAst(ast, moduleEntry, modules); CAstEntity fileEntity = null; try { fileEntity = xlatorToCAst.translateToCAst(); if (DEBUG) { CAstPrinter.printTo(fileEntity, new PrintWriter(System.err)); } topLevelEntities.add(Pair.make(fileEntity, moduleEntry)); } catch (TranslatorToCAst.Error e) { addMessages(moduleEntry, e.warning); } } } catch (final IOException e) { addMessage( moduleEntry, new Warning(Warning.SEVERE) { @Override public String getMsg() { return "I/O issue: " + e.getMessage(); } }); } catch (final RuntimeException e) { final ByteArrayOutputStream s = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(s); e.printStackTrace(ps); addMessage( moduleEntry, new Warning(Warning.SEVERE) { @Override public String getMsg() { return "Parsing issue: " + new String(s.toByteArray()); } }); } } /** * translate all relevant entities in the module to CAst, storing the results in topLevelEntities * * @param modules all modules in the analysis */ private void translateModuleToCAst( Module module, CAst ast, Set<Pair<CAstEntity, ModuleEntry>> topLevelEntities, List<Module> modules) { for (ModuleEntry me : Iterator2Iterable.make(module.getEntries())) { translateModuleEntryToCAst(me, ast, topLevelEntities, modules); } } public class DynamicCodeBody extends AstFunctionClass { private final WalkContext translationContext; private final CAstEntity entity; public DynamicCodeBody( TypeReference codeName, TypeReference parent, IClassLoader loader, CAstSourcePositionMap.Position sourcePosition, CAstEntity entity, WalkContext context) { super(codeName, parent, loader, sourcePosition); types.put(codeName.getName(), this); this.translationContext = context; this.entity = entity; } @Override public IClassHierarchy getClassHierarchy() { return cha; } public IMethod setCodeBody(DynamicMethodObject codeBody) { this.functionBody = codeBody; codeBody.entity = entity; codeBody.translationContext = translationContext; return codeBody; } @Override public Collection<Annotation> getAnnotations() { return Collections.emptySet(); } } public class DynamicMethodObject extends AstMethod implements Retranslatable { private WalkContext translationContext; private CAstEntity entity; public DynamicMethodObject( IClass cls, Collection<CAstQualifier> qualifiers, AbstractCFG<?, ?> cfg, SymbolTable symtab, boolean hasCatchBlock, Map<IBasicBlock<SSAInstruction>, TypeReference[]> caughtTypes, boolean hasMonitorOp, AstLexicalInformation lexicalInfo, DebuggingInformation debugInfo) { super( cls, qualifiers, cfg, symtab, AstMethodReference.fnReference(cls.getReference()), hasCatchBlock, caughtTypes, hasMonitorOp, lexicalInfo, debugInfo, null); // force creation of these constants by calling the getter methods symtab.getNullConstant(); } @Override public CAstEntity getEntity() { return entity; } @Override public void retranslate(AstTranslator xlator) { xlator.translate(entity, translationContext); } @Override public IClassHierarchy getClassHierarchy() { return cha; } @Override public String toString() { return "<Code body of " + cls + '>'; } @Override public TypeReference[] getDeclaredExceptions() { return null; } @Override public LexicalParent[] getParents() { if (lexicalInfo() == null) return new LexicalParent[0]; final String[] parents = lexicalInfo().getScopingParents(); if (parents == null) return new LexicalParent[0]; LexicalParent result[] = new LexicalParent[parents.length]; for (int i = 0; i < parents.length; i++) { final int hack = i; final AstMethod method = (AstMethod) lookupClass(parents[i], cha).getMethod(AstMethodReference.fnSelector); result[i] = new LexicalParent() { @Override public String getName() { return parents[hack]; } @Override public AstMethod getMethod() { return method; } }; if (AstTranslator.DEBUG_LEXICAL) { System.err.println(("parent " + result[i].getName() + " is " + result[i].getMethod())); } } return result; } @Override public String getLocalVariableName(int bcIndex, int localNumber) { return null; } @Override public boolean hasLocalVariableTable() { return false; } public int getMaxLocals() { Assertions.UNREACHABLE(); return -1; } public int getMaxStackHeight() { Assertions.UNREACHABLE(); return -1; } @Override public TypeReference getParameterType(int i) { if (i == 0) { return getDeclaringClass().getReference(); } else { return getDeclaringClass().getClassLoader().getLanguage().getRootType(); } } } public class CoreClass extends AstDynamicPropertyClass { private final TypeName superName; public CoreClass( TypeName name, TypeName superName, IClassLoader loader, CAstSourcePositionMap.Position sourcePosition) { super( sourcePosition, name, loader, (short) 0, Collections.emptyMap(), CAstAbstractModuleLoader.this.getLanguage().getRootType()); types.put(name, this); this.superName = superName; } @Override public IClassHierarchy getClassHierarchy() { return cha; } @Override public String toString() { return "Core[" + getReference().getName().toString().substring(1) + ']'; } @Override public Collection<IClass> getDirectInterfaces() { return Collections.emptySet(); } @Override public IClass getSuperclass() { return superName == null ? null : types.get(superName); } @Override public Collection<Annotation> getAnnotations() { return Collections.emptySet(); } } }
12,235
28.272727
99
java
WALA
WALA-master/cast/src/main/java/com/ibm/wala/cast/loader/DynamicCallSiteReference.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.cast.loader; import com.ibm.wala.cast.types.AstMethodReference; import com.ibm.wala.classLoader.CallSiteReference; import com.ibm.wala.shrike.shrikeBT.IInvokeInstruction; import com.ibm.wala.types.MethodReference; import com.ibm.wala.types.TypeReference; public class DynamicCallSiteReference extends CallSiteReference { // this must be distinct from java invoke codes. // see com.ibm.shrikeBT.BytecodeConstants public enum Dispatch implements IInvokeInstruction.IDispatch { JS_CALL; @Override public boolean hasImplicitThis() { return false; } } public DynamicCallSiteReference(MethodReference ref, int pc) { super(pc, ref); } public DynamicCallSiteReference(TypeReference ref, int pc) { this(AstMethodReference.fnReference(ref), pc); } @Override public IInvokeInstruction.IDispatch getInvocationCode() { return Dispatch.JS_CALL; } @Override protected String getInvocationString(IInvokeInstruction.IDispatch invocationCode) { return "Function"; } @Override public String toString() { return "JSCall@" + getProgramCounter(); } public CallSiteReference cloneReference(int pc) { return new DynamicCallSiteReference(getDeclaredTarget(), pc); } @Override public boolean isDispatch() { return true; } @Override public boolean isStatic() { return false; } @Override public boolean isFixed() { return false; } }
1,828
23.716216
85
java
WALA
WALA-master/cast/src/main/java/com/ibm/wala/cast/loader/SingleClassLoaderFactory.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.cast.loader; import com.ibm.wala.classLoader.ClassLoaderFactory; import com.ibm.wala.classLoader.IClassLoader; import com.ibm.wala.ipa.callgraph.AnalysisScope; import com.ibm.wala.ipa.cha.IClassHierarchy; import com.ibm.wala.ipa.summaries.BypassSyntheticClassLoader; import com.ibm.wala.types.ClassLoaderReference; import com.ibm.wala.util.debug.Assertions; /** * Abstract {@link ClassLoaderFactory} for languages modeled as having a single class loader. * Subclasses provide the logic to create the classloader. */ public abstract class SingleClassLoaderFactory implements ClassLoaderFactory { /** for caching the class loader, so we don't initialize more than once */ private IClassLoader THE_LOADER = null; /** Support synthetic classes */ private IClassLoader syntheticLoader; @Override public IClassLoader getLoader( ClassLoaderReference classLoaderReference, IClassHierarchy cha, AnalysisScope scope) { if (THE_LOADER == null) { THE_LOADER = makeTheLoader(cha); try { THE_LOADER.init(scope.getModules(getTheReference())); } catch (java.io.IOException e) { Assertions.UNREACHABLE(); } } if (classLoaderReference.equals(scope.getSyntheticLoader())) { syntheticLoader = new BypassSyntheticClassLoader( scope.getSyntheticLoader(), THE_LOADER, scope.getExclusions(), cha); return syntheticLoader; } else { assert classLoaderReference.equals(getTheReference()); return THE_LOADER; } } public IClassLoader getTheLoader() { return THE_LOADER; } /** get the reference to the single class loader for the language */ public abstract ClassLoaderReference getTheReference(); protected abstract IClassLoader makeTheLoader(IClassHierarchy cha); }
2,189
32.181818
93
java
WALA
WALA-master/cast/src/main/java/com/ibm/wala/cast/tree/CAst.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.cast.tree; import java.util.List; /** * The main interface for creating CAPA Abstract Syntax Trees. This interface provides essentially a * factory for creating AST nodes in a tree structure. There is no strong assumption about the * meaning of specific nodes; however, the `kind' argument to a makeNode call should be a value from * the constants in the CAstNode interface. The other arguments to makeNode calls are child nodes. * The structure of the tree is a matter of agreement between providers and consumers of specific * trees. * * @author Julian Dolby (dolby@us.ibm.com) */ public interface CAst { /** Make a node of type kind with no children. */ CAstNode makeNode(int kind); /** Make a node of type kind with one child. */ CAstNode makeNode(int kind, CAstNode c1); /** Make a node of type kind with two children. */ CAstNode makeNode(int kind, CAstNode c1, CAstNode c2); /** Make a node of type kind with three children. */ CAstNode makeNode(int kind, CAstNode c1, CAstNode c2, CAstNode c3); /** Make a node of type kind with four children. */ CAstNode makeNode(int kind, CAstNode c1, CAstNode c2, CAstNode c3, CAstNode c4); /** Make a node of type kind with five children. */ CAstNode makeNode(int kind, CAstNode c1, CAstNode c2, CAstNode c3, CAstNode c4, CAstNode c5); /** Make a node of type kind with six children. */ CAstNode makeNode( int kind, CAstNode c1, CAstNode c2, CAstNode c3, CAstNode c4, CAstNode c5, CAstNode c6); /** Make a node of type kind specifying an array of children. */ CAstNode makeNode(int kind, CAstNode... cs); /** Make a node of type kind giving a first child and array of the rest. */ CAstNode makeNode(int kind, CAstNode firstChild, CAstNode[] otherChildren); /** Make a node of type kind specifying a list of children. */ CAstNode makeNode(int kind, List<CAstNode> cs); /** Make a boolean constant node. */ CAstNode makeConstant(boolean value); /** Make a char constant node. */ CAstNode makeConstant(char value); /** Make a short integer constant node. */ CAstNode makeConstant(short value); /** Make an integer constant node. */ CAstNode makeConstant(int value); /** Make a long integer constant node. */ CAstNode makeConstant(long value); /** Make a double-precision floating point constant node. */ CAstNode makeConstant(double value); /** Make a single-precision floating point constant node. */ CAstNode makeConstant(float value); /** Make an arbitrary object constant node. */ CAstNode makeConstant(Object value); /** Make a new identifier, unqiue to this CAst instance. */ String makeUnique(); }
3,055
35.380952
100
java
WALA
WALA-master/cast/src/main/java/com/ibm/wala/cast/tree/CAstAnnotation.java
/* * Copyright (c) 2013 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.cast.tree; import java.util.Map; public interface CAstAnnotation { CAstType getType(); Map<String, Object> getArguments(); }
522
23.904762
72
java
WALA
WALA-master/cast/src/main/java/com/ibm/wala/cast/tree/CAstControlFlowMap.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.cast.tree; import java.util.Collection; /** * The control flow information for the CAPA AST of a particular entity. An ast may contain various * nodes that pertain to control flow---such as gotos, branches, exceptions and so on---and this map * denotes the target ast nodes of ast nodes that are control flow instructions. The label is fairly * arbitrary---it will depend on the language, producers and consumers of the tree---but is * generally expected to be things like case labels, exception types, conditional outcomes and so * on. * * @author Julian Dolby (dolby@us.ibm.com) */ public interface CAstControlFlowMap { /** * A distinguished label that means this control flow is the default target of a switch (or case) * statement as found in many procedural languages. */ Object SWITCH_DEFAULT = new Object(); /** A distinguished target that means this control flow is the target of an uncaught exception. */ CAstNode EXCEPTION_TO_EXIT = new CAstLeafNode() { @Override public int getKind() { return CAstNode.CONSTANT; } @Override public Object getValue() { return this; } @Override public String toString() { return "EXCEPTION_TO_EXIT"; } @Override public int hashCode() { return getKind() * toString().hashCode(); } @Override public boolean equals(Object o) { return o == this; } }; /** * Return the target ast node of the control-flow instruction denoted by from with respect to the * given label. */ CAstNode getTarget(CAstNode from, Object label); /** * Return a collection of all labels for which the control-flow ast node {@code from} has a * target. */ Collection<Object> getTargetLabels(CAstNode from); /** Return a collection of control-flow ast nodes that have this one as a possible target. */ Collection<Object> getSourceNodes(CAstNode to); /** * Returns an iterator of all CAstNodes for which this map contains control flow mapping * information. */ Collection<CAstNode> getMappedNodes(); }
2,568
29.951807
100
java
WALA
WALA-master/cast/src/main/java/com/ibm/wala/cast/tree/CAstEntity.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.cast.tree; import java.util.Collection; import java.util.Iterator; import java.util.Map; /** * The assumption is that abstract syntax trees pertain to particular programming language * constructs, such as classes, methods, programs and the like. Thus, the expectation is that users * of CAst will typically be communicating such entities, and this interface is meant to give them a * mechanism to do this. * * <p>The set of kinds that are currently in this file is not meant to be exhaustive, and should be * extended as needed for any new languages that come along. * * @author Julian Dolby (dolby@us.ibm.com) */ public interface CAstEntity { /** This entity is a function. Children: in JavaScript, FUNCTION_ENTITY's; in Java, none. */ int FUNCTION_ENTITY = 1; /** * This entity is a program script for a scripting language. Children: in JavaScript, * FUNCTION_ENTITY's(?); doesn't occur in Java. */ int SCRIPT_ENTITY = 2; /** * This entity is a type in an object-oriented language. Children: typically, immediately enclosed * FIELD_ENTITY's, FUNCTION_ENTITY's, and TYPE_ENTITY's. */ int TYPE_ENTITY = 3; /** This entity is a field in an object-oriented language. Children: usually, none */ int FIELD_ENTITY = 4; /** This entity is a source file (i.e. a compilation unit). */ int FILE_ENTITY = 5; /** This entity represents a rule in a logic language. */ int RULE_ENTITY = 6; /** * This entity is a macro. A macro is a code body that only makes sense when expanded in the * context of another code body. */ int MACRO_ENTITY = 7; /** This entity represents a global varible */ int GLOBAL_ENTITY = 8; /** * Languages that introduce new kinds of CAstEntity should use this number as the base of integers * chosen to denote the new entity types. */ int SUB_LANGUAGE_BASE = 100; /** * What kind of entity is this? The answer should be one of the constants in this file. This has * no meaning to the CAPA AST interfaces, but should be meaningful to a given producer and * consumer of an entity. */ int getKind(); /** * Some programming language constructs have names. This should be it, if appropriate, and null * otherwise. */ String getName(); /** * Some programming language constructs have signatures, which are like names but usually have * some detail to distinguish the construct from others with the same name. Signatures often * denote typing information as well, but this is not required. This method should return a * signature if appropriate, and null otherwise. */ String getSignature(); /** * Some programming language constructs have named arguments. This should be their names, if * appropriate. Otherwise, please return an array of size 0, since null can be a pain. */ String[] getArgumentNames(); /** * Some programming language constructs allow arguments to have default values. This should be * those defaults, one per named argument above. Otherwise, please return an array of size 0, * since null can be a pain. */ CAstNode[] getArgumentDefaults(); /** * Some programming language constructs have a specific number of arguments. This should be that * number, if appropriate, and 0 otherwise. */ int getArgumentCount(); /** * Some programming language constructs have a lexical structure. This should be those constructs * that are directly inside the current one. The result of this method is a map from source * construct to the set of entities induced by that construct. Entities induced by no particular * construct are mapped by the null key. */ Map<CAstNode, Collection<CAstEntity>> getAllScopedEntities(); /** * Some programming language constructs have a lexical structure. This should be those constructs * that are directly inside the current one. The result of this method is the scoped entities * induced by the construct `construct' (i.e. a node of the AST returned by * * <p>Enclosed entities not induced by a specific AST node are mapped by the construct 'null'. */ Iterator<CAstEntity> getScopedEntities(CAstNode construct); /** The CAPA AST of this entity. */ CAstNode getAST(); /** The control flow map for the CAPA AST of this entity. */ CAstControlFlowMap getControlFlow(); /** The map of CAstNodes to source positions for the CAPA AST of this entity. */ CAstSourcePositionMap getSourceMap(); /** The source position of this entity. */ CAstSourcePositionMap.Position getPosition(); /** The source position of the token denoting this entity's name. */ CAstSourcePositionMap.Position getNamePosition(); /** The source position of argument 'arg' this entity, if any; */ CAstSourcePositionMap.Position getPosition(int arg); /** * The map from CAstNodes to types. Valid for nodes that have an explicitly declared type (e.g. * local vars). */ CAstNodeTypeMap getNodeTypeMap(); /** * Returns an Iterator over the qualifiers of the given entity, if it has any, e.g., "final", * "private". */ Collection<CAstQualifier> getQualifiers(); /** The CAst type of this entity. */ CAstType getType(); /** Returns the set of any annotations this entity may have */ Collection<CAstAnnotation> getAnnotations(); /** Allow finding original entity after rewrites */ default CAstEntity getOriginal() { return this; } }
5,839
33.97006
100
java
WALA
WALA-master/cast/src/main/java/com/ibm/wala/cast/tree/CAstLeafNode.java
package com.ibm.wala.cast.tree; import java.util.Collections; import java.util.List; /** Convenience interface for implementing an AST node with no children */ public interface CAstLeafNode extends CAstNode { @Override default List<CAstNode> getChildren() { return Collections.emptyList(); } }
307
21
74
java
WALA
WALA-master/cast/src/main/java/com/ibm/wala/cast/tree/CAstMemberReference.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.cast.tree; public interface CAstMemberReference extends CAstReference { CAstMemberReference FUNCTION = new CAstMemberReference() { @Override public String member() { return "the function body"; } @Override public CAstType type() { return null; } @Override public String toString() { return "Any::FUNCTION CALL"; } @Override public int hashCode() { return toString().hashCode(); } @Override public boolean equals(Object o) { return o == this; } }; String member(); }
1,055
22.466667
72
java
WALA
WALA-master/cast/src/main/java/com/ibm/wala/cast/tree/CAstNode.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.cast.tree; import java.util.List; /** * This interface represents nodes of CAPA Abstract Syntax Trees. It is a deliberately minimal * interface, simply assuming that the nodes form a tree and have some minimal state at each node. * In particular, a node has a kind---which should be one of the symbolic constants in this * file---and potentially has child nodes, a constant values, or possibly both. * * <p>Note that there is no support for mutating these trees. This is deliberate, and should not be * changed. We do not want to force all clients of the capa ast to handle mutating programs. In * particular, the DOMO infrastructure has many forms of caching and other operations that rely on * the underlying program being immutable. If you need to mutate these trees for some reason---and * think carefully if you really need to, since this is meant to be essentially a wire format * between components---make specialized implementations that understand how to do that. * * <p>Also note that this interface does not assume that you need some great big class hierarchy to * structure types of nodes in an ast. Some people prefer such hierarchies as a matter of taste, but * this interface is designed to not inflict this design choice on others. * * <p>Finally note that the set of node types in this file is not meant to be exhaustive. As new * languages are added, feel free to add new nodes types as needed. * * @author Julian Dolby (dolby@us.ibm.com) * @author Robert M. Fuhrer (rfuhrer@watson.ibm.com) */ public interface CAstNode { // statement kinds /** * Represents a standard case statement. Children: * * <ul> * <li>condition expression * <li>BLOCK_STMT containing all the cases * </ul> */ int SWITCH = 1; /** * Represents a standard while loop. Children: * * <ul> * <li>expression denoting the loop condition * <li>statement denoting the loop body * </ul> */ int LOOP = 2; /** * Represents a block of sequential statements. Children: * * <ul> * <li>statement #1 * <li>statement #2 * <li>... * </ul> */ int BLOCK_STMT = 3; /** * Represents a standard try/catch statement. Note that while some languages choose to bundle * together the notion of try/catch and the notion of unwind-protect (aka 'finally'), the CAst * does not. There is a separate UNWIND node type. Children: * * <ul> * <li>the code of the try block. * <li>the code of the catch block * <li>... * </ul> */ int TRY = 4; /** * Represents an expression statement (e.g. "foo();"). Children: * * <ul> * <li>the expression * </ul> */ int EXPR_STMT = 5; int DECL_STMT = 6; int RETURN = 7; int GOTO = 8; int BREAK = 9; int CONTINUE = 10; int IF_STMT = 11; int THROW = 12; int FUNCTION_STMT = 13; int ASSIGN = 14; int ASSIGN_PRE_OP = 15; int ASSIGN_POST_OP = 16; int LABEL_STMT = 17; int IFGOTO = 18; int EMPTY = 19; int RETURN_WITHOUT_BRANCH = 20; int CATCH = 21; int UNWIND = 22; int MONITOR_ENTER = 23; int MONITOR_EXIT = 24; int ECHO = 25; int YIELD_STMT = 26; int FORIN_LOOP = 27; int GLOBAL_DECL = 28; int CLASS_STMT = 29; // expression kinds int FUNCTION_EXPR = 100; int EXPR_LIST = 101; int CALL = 102; int GET_CAUGHT_EXCEPTION = 103; /** * Represents a block of sequentially-executed nodes, the last of which produces the value for the * entire block (like progn from lisp). Children: * * <ul> * <li>node 1 * <li>node 2 * <li>... * <li>block value expression * </ul> */ int BLOCK_EXPR = 104; int BINARY_EXPR = 105; int UNARY_EXPR = 106; int IF_EXPR = 107; int ANDOR_EXPR = 108; // TODO blow away? int NEW = 109; int OBJECT_LITERAL = 110; int VAR = 111; int OBJECT_REF = 112; int CHOICE_EXPR = 113; int CHOICE_CASE = 114; int SUPER = 115; int THIS = 116; int ARRAY_LITERAL = 117; int CAST = 118; int INSTANCEOF = 119; int ARRAY_REF = 120; int ARRAY_LENGTH = 121; int TYPE_OF = 122; int EACH_ELEMENT_HAS_NEXT = 123; int EACH_ELEMENT_GET = 124; int LIST_EXPR = 125; int EMPTY_LIST_EXPR = 126; int TYPE_LITERAL_EXPR = 127; int IS_DEFINED_EXPR = 128; int MACRO_VAR = 129; int NARY_EXPR = 130; // new nodes with an explicit enclosing argument, e.g. "outer.new Inner()". They are mostly // treated the same, except in JavaCAst2IRTranslator.doNewObject int NEW_ENCLOSING = 131; int COMPREHENSION_EXPR = 132; // explicit lexical scopes int LOCAL_SCOPE = 200; int SPECIAL_PARENT_SCOPE = 201; // literal expression kinds int CONSTANT = 300; int OPERATOR = 301; // special stuff int PRIMITIVE = 400; int ERROR = 401; int VOID = 402; int ASSERT = 403; int INCLUDE = 404; int NAMED_ENTITY_REF = 405; int SUB_LANGUAGE_BASE = 1000; /** What kind of node is this? Should return some constant from this file. */ int getKind(); /** Returns the constant value represented by this node, if appropriate, and null otherwise. */ Object getValue(); /** * Return the nth child of this node. If there is no such child, this method should throw an * IndexOutOfBoundsException. */ default CAstNode getChild(int n) { return getChildren().get(n); } /** How many children does this node have? */ default int getChildCount() { return getChildren().size(); } List<CAstNode> getChildren(); }
5,857
27.163462
100
java
WALA
WALA-master/cast/src/main/java/com/ibm/wala/cast/tree/CAstNodeTypeMap.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ /* * Created on Aug 30, 2005 */ package com.ibm.wala.cast.tree; import java.util.Collection; public interface CAstNodeTypeMap { Collection<CAstNode> getMappedNodes(); CAstType getNodeType(CAstNode node); }
591
23.666667
72
java
WALA
WALA-master/cast/src/main/java/com/ibm/wala/cast/tree/CAstQualifier.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ /* * Created on Sep 1, 2005 */ package com.ibm.wala.cast.tree; import com.ibm.wala.util.collections.HashSetFactory; import java.util.Set; public class CAstQualifier { public static final Set /* <CAstQualifier> */<CAstQualifier> sQualifiers = HashSetFactory.make(); public static final CAstQualifier CONST = new CAstQualifier("const"); public static final CAstQualifier STRICTFP = new CAstQualifier("strictfp"); public static final CAstQualifier VOLATILE = new CAstQualifier("volatile"); public static final CAstQualifier ABSTRACT = new CAstQualifier("abstract"); public static final CAstQualifier INTERFACE = new CAstQualifier("interface"); public static final CAstQualifier NATIVE = new CAstQualifier("native"); public static final CAstQualifier TRANSIENT = new CAstQualifier("transient"); public static final CAstQualifier FINAL = new CAstQualifier("final"); public static final CAstQualifier STATIC = new CAstQualifier("static"); public static final CAstQualifier PRIVATE = new CAstQualifier("private"); public static final CAstQualifier PROTECTED = new CAstQualifier("protected"); public static final CAstQualifier PUBLIC = new CAstQualifier("public"); public static final CAstQualifier SYNCHRONIZED = new CAstQualifier("synchronized"); public static final CAstQualifier ANNOTATION = new CAstQualifier("@annotation"); public static final CAstQualifier ENUM = new CAstQualifier("enum"); public static final CAstQualifier MODULE = new CAstQualifier("module"); static { sQualifiers.add(ANNOTATION); sQualifiers.add(PUBLIC); sQualifiers.add(PROTECTED); sQualifiers.add(PRIVATE); sQualifiers.add(STATIC); sQualifiers.add(FINAL); sQualifiers.add(SYNCHRONIZED); sQualifiers.add(TRANSIENT); sQualifiers.add(NATIVE); sQualifiers.add(INTERFACE); sQualifiers.add(ABSTRACT); sQualifiers.add(VOLATILE); sQualifiers.add(STRICTFP); sQualifiers.add(CONST); sQualifiers.add(ENUM); sQualifiers.add(MODULE); } private static int sNextBitNum = 0; private final String fName; private final long fBit; public CAstQualifier(String name) { super(); fBit = 1L << sNextBitNum++; fName = name; sQualifiers.add(this); } public long getBit() { return fBit; } public String getName() { return fName; } @Override public boolean equals(Object o) { if (!(o instanceof CAstQualifier)) return false; CAstQualifier other = (CAstQualifier) o; return other.fName.equals(fName) && (fBit == other.fBit); } @Override public int hashCode() { int result = 37; result = result * 13 + fName.hashCode(); return result; } @Override public String toString() { return fName; } }
3,114
30.785714
99
java
WALA
WALA-master/cast/src/main/java/com/ibm/wala/cast/tree/CAstReference.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.cast.tree; /** * This interface is used to denote various kinds of references in CAst structures. It can be used * to denote types for languages like Java and PHP that have non-trivial mappings from names to * actual entities. * * @author Julian Dolby (dolby@us.ibm.com) */ public interface CAstReference { CAstType type(); }
732
29.541667
98
java
WALA
WALA-master/cast/src/main/java/com/ibm/wala/cast/tree/CAstSourcePositionMap.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.cast.tree; import com.ibm.wala.classLoader.IMethod.SourcePosition; import java.io.IOException; import java.io.Reader; import java.net.URL; import java.util.Iterator; import java.util.NavigableSet; /** * The assumption is that a typical CAst is derived from some kind of textual source file, for which * it makes sense to record source position in terms of line and column numbers. This interface * encapsulates a mapping from CAstNodes of the an ast to such source positions. * * @author Julian Dolby (dolby@us.ibm.com) */ public interface CAstSourcePositionMap { /** * This interface encapsulates the source position of an ast node in its source file. Since * different parsers record different degrees of source position information, any client of these * Positions must be prepared to expect -1---symbolizing no information---to be returned by some * or all of its accessors. * * @author Julian Dolby (dolby@us.ibm.com) */ interface Position extends SourcePosition { /** * Pretty print a source position * * @return pretty-printed string representation */ default String prettyPrint() { String file = getURL().getFile(); file = file.substring(file.lastIndexOf('/') + 1); int line = getFirstLine(), start_offset = getFirstOffset(), end_offset = getLastOffset(); return file + '@' + line + ':' + start_offset + '-' + end_offset; } URL getURL(); Reader getReader() throws IOException; } Position NO_INFORMATION = new Position() { @Override public String toString() { return "<no information>"; } @Override public int getFirstLine() { return -1; } @Override public int getLastLine() { return -1; } @Override public int getFirstCol() { return -1; } @Override public int getLastCol() { return -1; } @Override public int getFirstOffset() { return -1; } @Override public int getLastOffset() { return -1; } @Override public int compareTo(SourcePosition o) { return -1; } @Override public URL getURL() { return null; } @Override public Reader getReader() throws IOException { return new Reader() { @Override public int read(char[] cbuf, int off, int len) throws IOException { return -1; } @Override public void close() throws IOException {} }; } }; /** * Returns the position of a given node in its source file, or null if the position is not known * or does not exist. */ Position getPosition(CAstNode n); /** * Returns an iterator of all CAstNodes for which this map contains source mapping information. */ Iterator<CAstNode> getMappedNodes(); /** Returns an ordered set of all positions in this map. */ NavigableSet<Position> positions(); }
3,518
25.261194
100
java
WALA
WALA-master/cast/src/main/java/com/ibm/wala/cast/tree/CAstSymbol.java
/* * Copyright (c) 2013 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.cast.tree; public interface CAstSymbol { Object NULL_DEFAULT_VALUE = new Object() { @Override public String toString() { return "NULL DEFAULT VALUE"; } }; String name(); /** like final in Java; can only be declared / assigned once */ boolean isFinal(); boolean isCaseInsensitive(); Object defaultInitValue(); boolean isInternalName(); CAstType type(); }
813
21.611111
72
java
WALA
WALA-master/cast/src/main/java/com/ibm/wala/cast/tree/CAstType.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ /* * Created on Aug 30, 2005 */ package com.ibm.wala.cast.tree; import java.util.Collection; import java.util.Collections; import java.util.List; public interface CAstType { /** Returns the fully-qualified (e.g. bytecode-compliant for Java) type name. */ String getName(); Collection<CAstType> getSupertypes(); interface Primitive extends CAstType { // Need anything else? The name pretty much says it all... } interface Reference extends CAstType {} interface Class extends Reference { boolean isInterface(); Collection<CAstQualifier> getQualifiers(); } interface Array extends Reference { int getNumDimensions(); CAstType getElementType(); } interface Function extends Reference { CAstType getReturnType(); List<CAstType> getArgumentTypes(); Collection<CAstType> getExceptionTypes(); int getArgumentCount(); } interface Method extends Function { CAstType getDeclaringType(); boolean isStatic(); } interface Complex extends CAstType { CAstType getType(); } interface Union extends Complex { Iterable<CAstType> getConstituents(); } CAstType DYNAMIC = new CAstType() { @Override public String getName() { return "DYNAMIC"; } @Override public Collection<CAstType> /*<CAstType>*/ getSupertypes() { return Collections.emptySet(); } }; }
1,802
20.464286
82
java
WALA
WALA-master/cast/src/main/java/com/ibm/wala/cast/tree/CAstTypeDictionary.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ /* * Created on Aug 31, 2005 */ package com.ibm.wala.cast.tree; import java.util.Iterator; public interface CAstTypeDictionary /*<ASTType>*/ extends Iterable<CAstType> { CAstType getCAstTypeFor(Object /*ASTType*/ type); CAstReference resolveReference(CAstReference ref); @Override Iterator<CAstType> iterator(); }
704
25.111111
78
java
WALA
WALA-master/cast/src/main/java/com/ibm/wala/cast/tree/impl/AbstractSourcePosition.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.cast.tree.impl; import com.ibm.wala.cast.tree.CAstSourcePositionMap.Position; import com.ibm.wala.classLoader.IMethod.SourcePosition; import java.net.URL; public abstract class AbstractSourcePosition implements Position { @Override public boolean equals(Object o) { if (o instanceof Position) { Position p = (Position) o; return getFirstLine() == p.getFirstLine() && getLastLine() == p.getLastLine() && getFirstCol() == p.getFirstCol() && getLastCol() == p.getLastCol() && getFirstOffset() == p.getFirstOffset() && getLastOffset() == p.getLastOffset() && ((getURL() != null) ? ((Object) getURL()).toString().equals(((Object) p.getURL()).toString()) : p.getURL() == null); } else { return false; } } @Override public int hashCode() { return getFirstLine() * getLastLine() * getFirstCol() * getLastCol(); } @Override public int compareTo(SourcePosition o) { if (o instanceof Position) { Position p = (Position) o; if (getFirstLine() != p.getFirstLine()) { return getFirstLine() - p.getFirstLine(); } else if (getFirstCol() != p.getFirstCol()) { return getFirstCol() - p.getFirstCol(); } else if (getLastLine() != p.getLastLine()) { return getLastLine() - p.getLastLine(); } else { return getLastCol() - p.getLastCol(); } } else { return 0; } } @Override public String toString() { URL x = getURL(); String xf = x.toString(); if (xf.indexOf('/') >= 0) { xf = xf.substring(xf.lastIndexOf('/') + 1); } String pos; if (getFirstCol() != -1) { pos = "[" + getFirstLine() + ':' + getFirstCol() + "] -> [" + getLastLine() + ':' + getLastCol() + ']'; } else if (getFirstOffset() != -1) { pos = "[" + getFirstOffset() + "->" + getLastOffset() + "] (line " + getFirstLine() + ')'; } else { pos = "(line " + getFirstLine() + ')'; } return xf + ' ' + pos; } }
2,565
28.494253
96
java
WALA
WALA-master/cast/src/main/java/com/ibm/wala/cast/tree/impl/CAstControlFlowRecorder.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.cast.tree.impl; import com.ibm.wala.cast.tree.CAstControlFlowMap; import com.ibm.wala.cast.tree.CAstNode; import com.ibm.wala.cast.tree.CAstSourcePositionMap; import com.ibm.wala.util.collections.HashSetFactory; import java.util.Collection; import java.util.Collections; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.Map; import java.util.Objects; import java.util.Set; /** * An implementation of a CAstControlFlowMap that is designed to be used by producers of CAPA asts. * In addition to implementing the control flow map, it additionally allows clients to record * control flow mappings in terms of some arbitrary type object that are then mapped to CAstNodes by * the client. These objects can be anything, but one common use is that some type of parse tree is * walked to build a capa ast, with control flow being recorded in terms of parse tree nodes and * then ast nodes being mapped to parse tree nodes. * * <p>Note that, at present, support for mapping control flow on ast nodes directly is clunky. It is * necessary to establish that an ast nodes maps to itself, i.e. call xx.map(node, node). * * @author Julian Dolby (dolby@us.ibm.com) */ public class CAstControlFlowRecorder implements CAstControlFlowMap { private final CAstSourcePositionMap src; private final Map<CAstNode, Object> CAstToNode = new LinkedHashMap<>(); private final Map<Object, CAstNode> nodeToCAst = new LinkedHashMap<>(); private final Map<Key, Object> table = new LinkedHashMap<>(); private final Map<Object, Set<Object>> labelMap = new LinkedHashMap<>(); private final Map<Object, Set<Object>> sourceMap = new LinkedHashMap<>(); /** * for optimizing {@link #getMappedNodes()}; methods that change the set of mapped nodes should * null out this field */ private Collection<CAstNode> cachedMappedNodes = null; private static class Key { private final Object label; private final Object from; Key(Object label, Object from) { assert from != null; this.from = from; this.label = label; } @Override public int hashCode() { if (label != null) return from.hashCode() * label.hashCode(); else return from.hashCode(); } @Override public boolean equals(Object o) { return (o instanceof Key) && from == ((Key) o).from && Objects.equals(label, ((Key) o).label); } @Override public String toString() { return "<key " + label + " : " + from + '>'; } } public CAstControlFlowRecorder(CAstSourcePositionMap src) { this.src = src; map(EXCEPTION_TO_EXIT, EXCEPTION_TO_EXIT); } @Override public CAstNode getTarget(CAstNode from, Object label) { assert CAstToNode.get(from) != null; Key key = new Key(label, CAstToNode.get(from)); if (table.containsKey(key)) { Object target = table.get(key); assert nodeToCAst.containsKey(target); return nodeToCAst.get(target); } else return null; } @Override public Collection<Object> getTargetLabels(CAstNode from) { Object node = CAstToNode.get(from); Set<Object> found = labelMap.get(node); return found == null ? Collections.emptySet() : found; } @Override public Set<Object> getSourceNodes(CAstNode to) { Set<Object> found = sourceMap.get(CAstToNode.get(to)); return found == null ? Collections.emptySet() : found; } @Override public Collection<CAstNode> getMappedNodes() { Collection<CAstNode> nodes = cachedMappedNodes; if (nodes == null) { nodes = new LinkedHashSet<>(); for (Map.Entry<Key, Object> entry : table.entrySet()) { nodes.add(nodeToCAst.get(entry.getKey().from)); nodes.add(nodeToCAst.get(entry.getValue())); } cachedMappedNodes = nodes; } return nodes; } /** * Add a control-flow edge from the `from' node to the `to' node with the (possibly null) label * `label'. These nodes must be mapped by the client to CAstNodes using the `map' call; this * mapping can happen before or after this add call. */ public void add(Object from, Object to, Object label) { assert from != null; assert to != null; assert !((from instanceof CAstNode) && ((CAstNode) from).getKind() == CAstNode.GOTO && to == EXCEPTION_TO_EXIT); if (CAstToNode.containsKey(to)) { to = CAstToNode.get(to); } if (CAstToNode.containsKey(from)) { from = CAstToNode.get(from); } table.put(new Key(label, from), to); if (!labelMap.containsKey(from)) { labelMap.put(from, HashSetFactory.make(2)); } Set<Object> ls = labelMap.get(from); ls.add(label); if (!sourceMap.containsKey(to)) { sourceMap.put(to, HashSetFactory.make(2)); } Set<Object> ss = sourceMap.get(to); ss.add(from); } /** * Establish a mapping between some object `node' and the ast node `ast'. Objects used as * endpoints in a control flow edge must be mapped to ast nodes using this call. */ public void map(Object node, CAstNode ast) { assert node != null; assert ast != null; assert !nodeToCAst.containsKey(node) || nodeToCAst.get(node) == ast : node + " already mapped:\n" + this; assert !CAstToNode.containsKey(ast) || CAstToNode.get(ast) == node : ast + " already mapped:\n" + this; nodeToCAst.put(node, ast); cachedMappedNodes = null; CAstToNode.put(ast, node); } public void addAll(CAstControlFlowMap other) { for (CAstNode n : other.getMappedNodes()) { if (!CAstToNode.containsKey(n)) { map(n, n); } for (Object l : other.getTargetLabels(n)) { CAstNode to = other.getTarget(n, l); add(n, to, l); } } } public boolean isMapped(Object node) { return nodeToCAst.containsKey(node); } @Override public String toString() { StringBuilder sb = new StringBuilder("control flow map\n"); for (Map.Entry<Key, Object> entry : table.entrySet()) { final Key key = entry.getKey(); sb.append(key.from); if (src != null && nodeToCAst.get(key.from) != null && src.getPosition(nodeToCAst.get(key.from)) != null) { sb.append(" (").append(src.getPosition(nodeToCAst.get(key.from))).append(") "); } sb.append(" -- "); sb.append(key.label); sb.append(" --> "); sb.append(entry.getValue()); sb.append('\n'); } sb.append('\n'); return sb.toString(); } }
6,878
30.700461
100
java
WALA
WALA-master/cast/src/main/java/com/ibm/wala/cast/tree/impl/CAstImpl.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.cast.tree.impl; import com.ibm.wala.cast.tree.CAst; import com.ibm.wala.cast.tree.CAstLeafNode; import com.ibm.wala.cast.tree.CAstNode; import com.ibm.wala.cast.util.CAstPrinter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; /** * An implementation of CAst, i.e. a simple factory for creating capa ast nodes. This class simply * creates generic nodes with a kind field, and either an array of children or a constant values. * Note that there is no easy way to mutate these trees; do not change this (see CAstNode for the * rationale for this rule). * * @author Julian Dolby (dolby@us.ibm.com) */ public class CAstImpl implements CAst { private int nextID = 0; @Override public String makeUnique() { return "id" + nextID++; } protected static class CAstNodeImpl implements CAstNode { protected final List<CAstNode> cs; protected final int kind; protected CAstNodeImpl(int kind, List<CAstNode> cs) { this.kind = kind; this.cs = cs; for (int i = 0; i < cs.size(); i++) assert cs.get(i) != null : "argument " + i + " is null for node kind " + kind + " [" + CAstPrinter.entityKindAsString(kind) + ']'; } @Override public int getKind() { return kind; } @Override public Object getValue() { return null; } @Override public List<CAstNode> getChildren() { return cs; } @Override public String toString() { return System.identityHashCode(this) + ":" + CAstPrinter.print(this); } @Override public int hashCode() { int code = getKind() * (getChildCount() + 13); for (int i = 0; i < getChildCount() && i < 15; i++) { if (getChild(i) != null) { code *= getChild(i).getKind(); } } return code; } } @Override public CAstNode makeNode(final int kind, final List<CAstNode> cs) { return new CAstNodeImpl(kind, cs); } @Override public CAstNode makeNode(int kind, CAstNode c1, CAstNode[] cs) { List<CAstNode> children = new ArrayList<>(cs.length + 1); children.add(c1); children.addAll(Arrays.asList(cs)); return makeNode(kind, children); } @Override public CAstNode makeNode(int kind) { return makeNode(kind, Collections.emptyList()); } @Override public CAstNode makeNode(int kind, CAstNode c1) { return makeNode(kind, Collections.singletonList(c1)); } @Override public CAstNode makeNode(int kind, CAstNode c1, CAstNode c2) { return makeNode(kind, Arrays.asList(c1, c2)); } @Override public CAstNode makeNode(int kind, CAstNode c1, CAstNode c2, CAstNode c3) { return makeNode(kind, Arrays.asList(c1, c2, c3)); } @Override public CAstNode makeNode(int kind, CAstNode c1, CAstNode c2, CAstNode c3, CAstNode c4) { return makeNode(kind, Arrays.asList(c1, c2, c3, c4)); } @Override public CAstNode makeNode( int kind, CAstNode c1, CAstNode c2, CAstNode c3, CAstNode c4, CAstNode c5) { return makeNode(kind, Arrays.asList(c1, c2, c3, c4, c5)); } @Override public CAstNode makeNode( int kind, CAstNode c1, CAstNode c2, CAstNode c3, CAstNode c4, CAstNode c5, CAstNode c6) { return makeNode(kind, Arrays.asList(c1, c2, c3, c4, c5, c6)); } @Override public CAstNode makeNode(int kind, CAstNode... cs) { return makeNode(kind, Arrays.asList(cs)); } protected static class CAstValueImpl implements CAstLeafNode { protected final Object value; protected CAstValueImpl(Object value) { this.value = value; } @Override public int getKind() { return CAstNode.CONSTANT; } @Override public Object getValue() { return value; } @Override public String toString() { return "CAstValue: " + value; } @Override public int hashCode() { return System.identityHashCode(this) * ((value == null) ? 1 : System.identityHashCode(value)); } } @Override public CAstNode makeConstant(final Object value) { return new CAstValueImpl(value); } @Override public CAstNode makeConstant(boolean value) { return makeConstant(value ? Boolean.TRUE : Boolean.FALSE); } @Override public CAstNode makeConstant(char value) { return makeConstant(Character.valueOf(value)); } @Override public CAstNode makeConstant(short value) { return makeConstant(Short.valueOf(value)); } @Override public CAstNode makeConstant(int value) { return makeConstant(Integer.valueOf(value)); } @Override public CAstNode makeConstant(long value) { return makeConstant(Long.valueOf(value)); } @Override public CAstNode makeConstant(float value) { return makeConstant(Float.valueOf(value)); } @Override public CAstNode makeConstant(double value) { return makeConstant(Double.valueOf(value)); } }
5,398
24.228972
100
java
WALA
WALA-master/cast/src/main/java/com/ibm/wala/cast/tree/impl/CAstNodeTypeMapRecorder.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ /* * Created on Oct 10, 2005 */ package com.ibm.wala.cast.tree.impl; import com.ibm.wala.cast.tree.CAstNode; import com.ibm.wala.cast.tree.CAstNodeTypeMap; import com.ibm.wala.cast.tree.CAstType; import java.util.Collection; import java.util.HashMap; public class CAstNodeTypeMapRecorder extends HashMap<CAstNode, CAstType> implements CAstNodeTypeMap { private static final long serialVersionUID = 7812144102027916961L; @Override public CAstType getNodeType(CAstNode node) { return get(node); } public void add(CAstNode node, CAstType type) { put(node, type); } @Override public Collection<CAstNode> getMappedNodes() { return keySet(); } public void addAll(CAstNodeTypeMap other) { for (CAstNode o : other.getMappedNodes()) { put(o, other.getNodeType(o)); } } }
1,197
25.043478
72
java
WALA
WALA-master/cast/src/main/java/com/ibm/wala/cast/tree/impl/CAstOperator.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.cast.tree.impl; import com.ibm.wala.cast.tree.CAstLeafNode; import com.ibm.wala.cast.tree.CAstNode; /** * Various operators that are built in to many languages, and hence perhaps deserve special notice * in WALA CAst interface. There is no strong notion of what should be in here, so feel free to add * other common operators. * * @author Julian Dolby (dolby@us.ibm.com) */ public class CAstOperator implements CAstLeafNode { private final String op; protected CAstOperator(String op) { this.op = op; } @Override public String toString() { return "OP:" + op; } @Override public int getKind() { return CAstNode.OPERATOR; } @Override public Object getValue() { return op; } /* * The EQ and STRICT_EQ and NE and STRICT_NE pairs of operators are meant to * support languages that define multiple notions of equality, such as Scheme with * eql and eq and JavaScript with == and ===. */ public static final CAstOperator OP_EQ = new CAstOperator("=="); public static final CAstOperator OP_STRICT_EQ = new CAstOperator("==="); public static final CAstOperator OP_NE = new CAstOperator("!="); public static final CAstOperator OP_STRICT_NE = new CAstOperator("!=="); public static final CAstOperator OP_ADD = new CAstOperator("+"); public static final CAstOperator OP_CONCAT = new CAstOperator("."); public static final CAstOperator OP_DIV = new CAstOperator("/"); public static final CAstOperator OP_LSH = new CAstOperator("<<"); public static final CAstOperator OP_MOD = new CAstOperator("%"); public static final CAstOperator OP_MUL = new CAstOperator("*"); public static final CAstOperator OP_POW = new CAstOperator("^^^"); public static final CAstOperator OP_RSH = new CAstOperator(">>"); public static final CAstOperator OP_URSH = new CAstOperator(">>>"); public static final CAstOperator OP_SUB = new CAstOperator("-"); public static final CAstOperator OP_GE = new CAstOperator(">="); public static final CAstOperator OP_GT = new CAstOperator(">"); public static final CAstOperator OP_LE = new CAstOperator("<="); public static final CAstOperator OP_LT = new CAstOperator("<"); public static final CAstOperator OP_NOT = new CAstOperator("!"); public static final CAstOperator OP_BITNOT = new CAstOperator("~"); public static final CAstOperator OP_BIT_AND = new CAstOperator("&"); public static final CAstOperator OP_REL_AND = new CAstOperator("&&"); public static final CAstOperator OP_BIT_OR = new CAstOperator("|"); public static final CAstOperator OP_REL_OR = new CAstOperator("||"); public static final CAstOperator OP_BIT_XOR = new CAstOperator("^"); public static final CAstOperator OP_REL_XOR = new CAstOperator("^^"); public static final CAstOperator OP_IN = new CAstOperator("in"); public static final CAstOperator OP_NOT_IN = new CAstOperator("not in"); }
3,285
39.567901
99
java
WALA
WALA-master/cast/src/main/java/com/ibm/wala/cast/tree/impl/CAstSourcePositionRecorder.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.cast.tree.impl; import com.ibm.wala.cast.tree.CAstNode; import com.ibm.wala.cast.tree.CAstSourcePositionMap; import com.ibm.wala.util.collections.HashMapFactory; import com.ibm.wala.util.collections.Iterator2Iterable; import java.io.IOException; import java.io.InputStreamReader; import java.io.Reader; import java.net.MalformedURLException; import java.net.URL; import java.util.Iterator; import java.util.Map; import java.util.NavigableSet; import java.util.TreeSet; public class CAstSourcePositionRecorder implements CAstSourcePositionMap { private final Map<CAstNode, Position> positions = HashMapFactory.make(); @Override public Position getPosition(CAstNode n) { return positions.get(n); } @Override public Iterator<CAstNode> getMappedNodes() { return positions.keySet().iterator(); } public void setPosition(CAstNode n, Position p) { positions.put(n, p); } public void setPosition( CAstNode n, final int fl, final int fc, final int ll, final int lc, final String url, final String file) throws MalformedURLException { setPosition(n, fl, fc, ll, lc, new URL(url), new URL(file)); } public void setPosition( CAstNode n, final int fl, final int fc, final int ll, final int lc, final URL url, final URL file) { setPosition( n, new AbstractSourcePosition() { @Override public int getFirstLine() { return fl; } @Override public int getLastLine() { return ll; } @Override public int getFirstCol() { return fc; } @Override public int getLastCol() { return lc; } @Override public int getFirstOffset() { return -1; } @Override public int getLastOffset() { return -1; } @Override public URL getURL() { return url; } @Override public Reader getReader() throws IOException { return new InputStreamReader(file.openConnection().getInputStream()); } @Override public String toString() { return "[" + fl + ':' + fc + "]->[" + ll + ':' + lc + ']'; } }); } public void setPosition(CAstNode n, int lineNumber, String url, String file) throws MalformedURLException { setPosition(n, lineNumber, new URL(url), new URL(file)); } public void setPosition(CAstNode n, int lineNumber, URL url, URL file) { setPosition(n, new LineNumberPosition(url, file, lineNumber)); } public void addAll(CAstSourcePositionMap other) { for (CAstNode node : Iterator2Iterable.make(other.getMappedNodes())) { setPosition(node, other.getPosition(node)); } } @Override public NavigableSet<Position> positions() { return new TreeSet<>(positions.values()); } }
3,423
24.362963
81
java
WALA
WALA-master/cast/src/main/java/com/ibm/wala/cast/tree/impl/CAstSymbolImpl.java
/* * Copyright (c) 2013 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.cast.tree.impl; import com.ibm.wala.cast.tree.CAstType; public class CAstSymbolImpl extends CAstSymbolImplBase { public CAstSymbolImpl(String _name, CAstType type) { super(_name, type); } public CAstSymbolImpl(String _name, CAstType type, boolean _isFinal) { super(_name, type, _isFinal); } public CAstSymbolImpl(String _name, CAstType type, boolean _isFinal, boolean _isCaseInsensitive) { super(_name, type, _isFinal, _isCaseInsensitive); } public CAstSymbolImpl(String _name, CAstType type, Object _defaultInitValue) { super(_name, type, _defaultInitValue); } public CAstSymbolImpl(String _name, CAstType type, boolean _isFinal, Object _defaultInitValue) { super(_name, type, _isFinal, _defaultInitValue); } public CAstSymbolImpl( String _name, CAstType type, boolean _isFinal, boolean _isCaseInsensitive, Object _defaultInitValue) { super(_name, type, _isFinal, _isCaseInsensitive, _defaultInitValue); } @Override public boolean isInternalName() { return false; } }
1,454
28.1
100
java
WALA
WALA-master/cast/src/main/java/com/ibm/wala/cast/tree/impl/CAstSymbolImplBase.java
/* * Copyright (c) 2013 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.cast.tree.impl; import com.ibm.wala.cast.tree.CAstSymbol; import com.ibm.wala.cast.tree.CAstType; public abstract class CAstSymbolImplBase implements CAstSymbol { private final String _name; private final boolean _isFinal; private final boolean _isCaseInsensitive; private final Object _defaultInitValue; private final CAstType type; public CAstSymbolImplBase(String name, CAstType type) { this(name, type, false); } public CAstSymbolImplBase(String name, CAstType type, boolean isFinal) { this(name, type, isFinal, false); } public CAstSymbolImplBase(String name, CAstType type, boolean isFinal, boolean isCaseSensitive) { this(name, type, isFinal, isCaseSensitive, null); } public CAstSymbolImplBase(String name, CAstType type, Object defaultInitValue) { this(name, type, false, defaultInitValue); } public CAstSymbolImplBase(String name, CAstType type, boolean isFinal, Object defaultInitValue) { this(name, type, isFinal, false, defaultInitValue); } public CAstSymbolImplBase( String name, CAstType type, boolean isFinal, boolean isCaseSensitive, Object defaultInitValue) { this._name = name; this.type = type; this._isFinal = isFinal; this._isCaseInsensitive = isCaseSensitive; this._defaultInitValue = defaultInitValue; assert name != null; assert type != null; } @Override public CAstType type() { return type; } @Override public String name() { return _name; } @Override public boolean isFinal() { return _isFinal; } @Override public boolean isCaseInsensitive() { return _isCaseInsensitive; } @Override public Object defaultInitValue() { return _defaultInitValue; } @Override public abstract boolean isInternalName(); @Override public String toString() { return _name; } }
2,262
23.597826
99
java
WALA
WALA-master/cast/src/main/java/com/ibm/wala/cast/tree/impl/CAstTypeDictionaryImpl.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ /* * Created on Sep 21, 2005 */ package com.ibm.wala.cast.tree.impl; import com.ibm.wala.cast.tree.CAstReference; import com.ibm.wala.cast.tree.CAstType; import com.ibm.wala.cast.tree.CAstTypeDictionary; import com.ibm.wala.util.collections.HashMapFactory; import java.util.Iterator; import java.util.Map; public class CAstTypeDictionaryImpl<A> implements CAstTypeDictionary { protected final Map<A, CAstType> fMap = HashMapFactory.make(); @Override public CAstType getCAstTypeFor(Object astType) { return fMap.get(astType); } public void map(A astType, CAstType castType) { fMap.put(astType, castType); } @Override public Iterator<CAstType> iterator() { return fMap.values().iterator(); } @Override public CAstReference resolveReference(CAstReference ref) { return ref; } }
1,198
25.644444
72
java
WALA
WALA-master/cast/src/main/java/com/ibm/wala/cast/tree/impl/CAstValueImpl.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.cast.tree.impl; import com.ibm.wala.cast.tree.CAstNode; import java.util.List; /** * An implementation of CAst, i.e. a simple factory for creating capa ast nodes. This class simply * creates generic nodes with a kind field, and either an array of children. Note that there is no * easy way to mutate these trees; do not changes this (see CAstNode for the rationale for this * rule). * * @author Julian Dolby (dolby@us.ibm.com) */ public class CAstValueImpl extends CAstImpl { protected static class CAstNodeValueImpl extends CAstNodeImpl { protected CAstNodeValueImpl(int kind, List<CAstNode> cs) { super(kind, cs); } @Override public int hashCode() { int value = 1237 * kind; for (CAstNode element : cs) value *= element.hashCode(); return value; } @Override public boolean equals(Object o) { if (!(o instanceof CAstNode)) return false; final CAstNode otherNode = (CAstNode) o; if (kind != otherNode.getKind()) return false; if (!getChildren().equals(otherNode.getChildren())) return false; return true; } } @Override public CAstNode makeNode(final int kind, final List<CAstNode> cs) { return new CAstNodeValueImpl(kind, cs); } protected static class CAstValueValueImpl extends CAstValueImpl { protected CAstValueValueImpl(Object value) { super(value); } @Override public int hashCode() { return value.hashCode(); } @Override public boolean equals(Object o) { if (o instanceof CAstNode) { return value == null ? ((CAstNode) o).getValue() == null : value.equals(((CAstNode) o).getValue()); } else { return false; } } } @Override public CAstNode makeConstant(final Object value) { return new CAstValueValueImpl(value); } }
2,254
26.168675
98
java
WALA
WALA-master/cast/src/main/java/com/ibm/wala/cast/tree/impl/DelegatingEntity.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.cast.tree.impl; import com.ibm.wala.cast.tree.CAstAnnotation; import com.ibm.wala.cast.tree.CAstControlFlowMap; import com.ibm.wala.cast.tree.CAstEntity; import com.ibm.wala.cast.tree.CAstNode; import com.ibm.wala.cast.tree.CAstNodeTypeMap; import com.ibm.wala.cast.tree.CAstQualifier; import com.ibm.wala.cast.tree.CAstSourcePositionMap; import com.ibm.wala.cast.tree.CAstSourcePositionMap.Position; import com.ibm.wala.cast.tree.CAstType; import java.util.Collection; import java.util.Iterator; import java.util.Map; public class DelegatingEntity implements CAstEntity { private final CAstEntity base; public DelegatingEntity(CAstEntity base) { this.base = base; } @Override public CAstEntity getOriginal() { return base.getOriginal(); } @Override public int getKind() { return base.getKind(); } @Override public String getName() { return base.getName(); } @Override public String getSignature() { return base.getSignature(); } @Override public String[] getArgumentNames() { return base.getArgumentNames(); } @Override public CAstNode[] getArgumentDefaults() { return base.getArgumentDefaults(); } @Override public int getArgumentCount() { return base.getArgumentCount(); } @Override public Map<CAstNode, Collection<CAstEntity>> getAllScopedEntities() { return base.getAllScopedEntities(); } @Override public Iterator<CAstEntity> getScopedEntities(CAstNode construct) { return base.getScopedEntities(construct); } @Override public CAstNode getAST() { return base.getAST(); } @Override public CAstControlFlowMap getControlFlow() { return base.getControlFlow(); } @Override public CAstSourcePositionMap getSourceMap() { return base.getSourceMap(); } @Override public CAstSourcePositionMap.Position getPosition() { return base.getPosition(); } @Override public CAstNodeTypeMap getNodeTypeMap() { return base.getNodeTypeMap(); } @Override public Collection<CAstQualifier> getQualifiers() { return base.getQualifiers(); } @Override public CAstType getType() { return base.getType(); } @Override public Collection<CAstAnnotation> getAnnotations() { return base.getAnnotations(); } @Override public Position getPosition(int arg) { return base.getPosition(arg); } @Override public Position getNamePosition() { return base.getNamePosition(); } }
2,857
21.328125
72
java
WALA
WALA-master/cast/src/main/java/com/ibm/wala/cast/tree/impl/LineNumberPosition.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.cast.tree.impl; import java.io.IOException; import java.io.InputStreamReader; import java.io.Reader; import java.net.URL; public class LineNumberPosition extends AbstractSourcePosition { private final URL url; private final URL localFile; private final int lineNumber; public LineNumberPosition(URL url, URL localFile, int lineNumber) { this.url = url; this.localFile = localFile; this.lineNumber = lineNumber; } @Override public int getFirstLine() { return lineNumber; } @Override public int getLastLine() { return lineNumber; } @Override public int getFirstCol() { return -1; } @Override public int getLastCol() { return -1; } @Override public int getFirstOffset() { return -1; } @Override public int getLastOffset() { return -1; } @Override public URL getURL() { return url; } @Override public Reader getReader() throws IOException { return new InputStreamReader(localFile.openConnection().getInputStream()); } @Override public String toString() { String nm = url.getFile(); nm = nm.substring(nm.lastIndexOf('/') + 1); return '[' + nm + ':' + lineNumber + ']'; } }
1,596
20.013158
78
java
WALA
WALA-master/cast/src/main/java/com/ibm/wala/cast/tree/impl/RangePosition.java
/* * Copyright (c) 2007 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.cast.tree.impl; import com.ibm.wala.cast.tree.CAstSourcePositionMap.Position; import com.ibm.wala.classLoader.IMethod.SourcePosition; import java.io.IOException; import java.io.InputStreamReader; import java.io.Reader; import java.net.URL; public class RangePosition extends AbstractSourcePosition { private final URL url; private final int startLine; private final int endLine; private final int startOffset; private final int endOffset; public RangePosition(URL url, int startLine, int endLine, int startOffset, int endOffset) { super(); this.url = url; this.startLine = startLine; this.endLine = endLine; this.startOffset = startOffset; this.endOffset = endOffset; } public RangePosition(URL url, int line, int startOffset, int endOffset) { this(url, line, -1, startOffset, endOffset); } @Override public int compareTo(SourcePosition o) { Position other = (Position) o; if (startOffset != other.getFirstOffset()) { return startOffset - other.getFirstOffset(); } else { return endOffset - other.getLastOffset(); } } @Override public int getFirstLine() { return startLine; } @Override public int getLastLine() { return endLine; } @Override public int getFirstCol() { return -1; } @Override public int getLastCol() { return -1; } @Override public int getFirstOffset() { return startOffset; } @Override public int getLastOffset() { return endOffset; } @Override public URL getURL() { return url; } @Override public Reader getReader() throws IOException { return new InputStreamReader(url.openStream()); } }
2,068
21.988889
93
java