Skip to content

Instantly share code, notes, and snippets.

@rightfold
Last active August 29, 2015 14:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rightfold/e802797071504d72b260 to your computer and use it in GitHub Desktop.
Save rightfold/e802797071504d72b260 to your computer and use it in GitHub Desktop.
class SSA {
class InstructionID
class BlockID
sealed abstract class Instruction {
def referencedBlocks: Set[BlockID]
def referencedInstructions: Set[InstructionID]
}
case class UnconditionalJump(targetID: BlockID) extends Instruction {
override def referencedBlocks = Set(targetID)
override def referencedInstructions = Set.empty
}
type Block = Vector[(InstructionID, Instruction)]
case class CFG(blocks: Map[BlockID, Block]) {
def addBlock(): (BlockID, CFG) = {
val blockID = new BlockID
(blockID, copy(blocks = blocks + (blockID -> new Block)))
}
def addInstruction(blockID: BlockID, instruction: Instruction): (InstructionID, CFG) = {
val instructionID = new InstructionID
(instructionID, copy(blocks = blocks + (blockID -> blocks(blockID) :+ (instructionID -> instruction))))
}
}
object CFG {
def apply() = CFG(Map.empty)
}
}
val ssa = new SSA
val cfg = ssa.CFG()
// example:
// infinite loop between two blocks
val (blockID1, cfg2) = cfg.addBlock()
val (blockID2, cfg3) = cfg2.addBlock()
val (_, cfg3) = cfg2.addInstruction(blockID1, ssa.UnconditionalJump(blockID2))
val (_, cfg4) = cfg3.addInstruction(blockID2, ssa.UnconditionalJump(blockID1))
return cfg4
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment