private static void DeadCodeElimination(IRGraph graph) { Dictionary <Ident, IRIdent> identAnalysis = SimpleVariableAnalysis(graph); Queue <Ident> worklist = new Queue <Ident>(identAnalysis.Keys); while (worklist.Count > 0) { Ident ident = worklist.Dequeue(); IRIdent identObj = identAnalysis[ident]; if (identObj.CountUsesites() == 0) { IRTuple defStatement = identObj.GetDefsite(); if (!defStatement.HasSideEffects()) { Console.WriteLine("SSA: Deleting tuple: " + defStatement.toString() + " as it is dead code"); HashSet <Ident> usedVars = defStatement.GetUsedVars(); foreach (Ident used in usedVars) { IRIdent usedObj = identAnalysis[used]; usedObj.DeleteUsesite(defStatement); worklist.Enqueue(used); } graph.RemoveStatement(defStatement); } } } }
// Backward pass to determine liveness at each point in the block public void ComputeLiveouts() { this.liveouts.Clear(); Stack <List <string> > reversed = new Stack <List <string> >(); // Because this is a backward pass, lists will be found in reverse HashSet <Ident> lo = new HashSet <Ident>(this.liveout); // Extract liveness information for last statement in block IRTuple last = this.statements[this.statements.Count - 1]; HashSet <Ident> prevdef = last.GetDefinedVars(); string deflabel = ""; foreach (Ident ident in prevdef) { deflabel = ident; } HashSet <Ident> prevused = last.GetUsedVars(); List <string> lastliveout = new List <string>(); lastliveout.Add(deflabel); foreach (Ident ident in lo) { lastliveout.Add(ident); } reversed.Push(lastliveout); Console.WriteLine(); for (int i = this.statements.Count - 2; i >= 0; i--) // Start from second-last statement, as we already have liveout for last one { IRTuple tup = this.statements[i]; if (lo.Contains(deflabel)) { lo.Remove(deflabel); // Remove whatever is defined in the next statement } foreach (Ident ident in prevused) { if (!lo.Contains(ident)) { lo.Add(ident); // Add whatever is used in the next statement } } deflabel = ""; prevdef = tup.GetDefinedVars(); foreach (Ident ident in prevdef) { deflabel = ident; } prevused = tup.GetUsedVars(); List <string> currentliveout = new List <string>(); currentliveout.Add(deflabel); foreach (Ident ident in lo) { currentliveout.Add(ident); } reversed.Push(currentliveout); } while (reversed.Count > 0) { this.liveouts.Add(reversed.Pop()); } }